Replace Image with New Image in PowerPoint in C#

2018-09-14 06:39:45 Written by  support iceblue
Rate this item
(0 votes)

This article demonstrates how to replace an existing image with a new image in a PowerPoint document using Spire.Presentation.

The original image:

Replace Image with New Image in PowerPoint in C#

Detail steps:

Step 1: Instantiate a Presentation object and load the PowerPoint file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Input.pptx");

Step 2: Get the first slide.

ISlide slide = ppt.Slides[0];

Step 3: Append a new image to replace an existing image.

IImageData image = ppt.Images.Append(Image.FromFile("timg.jpg"));

Step 4: Replace the image which title is "image1" with the new image.

foreach (IShape shape in slide.Shapes)
{
    if (shape is SlidePicture)
    {
        if (shape.AlternativeTitle == "image1")
        {
            (shape as SlidePicture).PictureFill.Picture.EmbedImage = image;
        }
    }
}

Step 5: Save the file.

ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);

Screenshot after replacing image:

Replace Image with New Image in PowerPoint in C#

Full code:

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace ReplaceImage
{

    class Program
    {

        static void Main(string[] args)
        {
            {
                Presentation ppt = new Presentation();
                ppt.LoadFromFile("Input.pptx");

                ISlide slide = ppt.Slides[0];

                IImageData image = ppt.Images.Append(Image.FromFile("timg.jpg"));

                foreach (IShape shape in slide.Shapes)
                {
                    if (shape is SlidePicture)
                    {
                        if (shape.AlternativeTitle == "image1")
                        {
                            (shape as SlidePicture).PictureFill.Picture.EmbedImage = image;
                        }
                    }
                }

                ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);



            }
        }

    }
}

Additional Info

  • tutorial_title:
Last modified on Friday, 24 September 2021 09:19