We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

How do I replace a specific image in ppt with the passed image?

Hi,


I tried below code,
Presentation presentation = new Presentation(“Sample.pptx”);

//the first way
System.Drawing.Image newImage = System.Drawing.Image.FromFile(“SampleImages.jpg”);
IPPImage oldImage = presentation.Images[2];
oldImage.ReplaceImage(newImage);

presentation.Save(“BIO.pptx”, SaveFormat.Pptx);

But it is replacing some other image, how do i identify the image[id] of the particular image?

Hi,

I have observed your requirements and like to share that Presentation.Images is returns IEnumerable collection of images inside presentation. You can first find the image that you want to replace from respective shape and then find the index of the image inside images collection. Once index is obtained, you can add new image on that index to replace. Can you please try using following sample code on your end.

public static int GetImageID(IPPImage image, IEnumerable imageCollection)
{
int i=0;
foreach (var img in imageCollection)
{
if (image.Equals(image))
{
return i;
}
i++;
}

return -1;
}

public static void ReplaceImage()
{
Presentation presentation = new Presentation(“Sample.pptx”);

//the first way
System.Drawing.Image newImage = System.Drawing.Image.FromFile(“SampleImages.jpg”);

ISlide slide = presentation.Slides[0];

//IEnumerable image =
IEnumerable imageCollection = presentation.Images;

//PicFrame with desired image that you want to replace
IPictureFrame picFrame =(IPictureFrame) slide.Shapes[0];

//Getting image to replace
IPPImage ImageToReplace = picFrame.PictureFormat.Picture.Image;


int ID = GetImageID(ImageToReplace, imageCollection);

if (ID != -1)
{

IPPImage oldImage = presentation.Images[ID];
oldImage.ReplaceImage(newImage);
}
presentation.Save(“BIO.pptx”, Aspose.Slides.Export.SaveFormat.Pptx);
}

Many Thanks,

Hi Mudassir,


Thanks for your reply and sample code. It was very useful for me to understand the concept. I tried it but the image was not getting replaced. Below code resolved my issue.

public static void TestImageReplace()
{
Presentation pres= new Presentation(“Sample.pptx”);
foreach (var slide in pres.Slides)
{
foreach (var shape in slide.Shapes)
{
if (shape.GetType().ToString()== “Aspose.Slides.PictureFrame”)
{
IPictureFrame picFrame = (IPictureFrame)shape;
System.Drawing.Image newImage = System.Drawing.Image.FromFile(“SampleImage.jpg”);
IPPImage oldImage = picFrame.PictureFormat.Picture.Image;
oldImage.ReplaceImage(newImage);
}
}
}
pres.Save(“Sample.pptx”, SaveFormat.Pptx);
}

Hi,

It is good to know that approach worked on your end. I in fact shared the sample code in accordance to your requirements of getting Image ID. Please share, if I may help you further in this regard.

Many Thanks,