Tuesday, 03 September 2019 06:59

Replace an Image in PowerPoint in Java

Written by  support iceblue
Rate this item
(0 votes)

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

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;

public class ReplaceImage {

    public static void main(String[] args) throws Exception {

        //create a Presentation object
        Presentation presentation= new Presentation();

        //load the sample PowerPoint file
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");

        //add an image to the image collection
        String imagePath = "C:\\Users\\Administrator\\Desktop\\Microsoft-PowerPoint-logo.jpg";
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath));
        IImageData image = presentation.getImages().append(bufferedImage);

        //get the shape collection from the first slide
        ShapeCollection shapes = presentation.getSlides().get(0).getShapes();

        //loop through the shape collection
        for (int i = 0; i < shapes.getCount(); i++) {

            //determine if a shape is a picture
            if (shapes.get(i) instanceof SlidePicture) {

                //fill the shape with a new image
               ((SlidePicture) shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);
            }
        }
        
        //save to file
        presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013);
    }
}

Replace an Image in PowerPoint in Java

Additional Info

  • tutorial_title:
Last modified on Tuesday, 03 September 2019 07:03