In the process of daily work, we may sometimes encounter a situation where we need to replace the image in a PowerPoint document. And Free Spire.Presentation for Java provides us a method to replace an existing image with a new image in Java application. In this article, I will share the Java code used.
Import Jar Dependency
Method 1: Download the Free Spire.Presentation for Java and unzip it. Then add the Spire.Presentation.jar file to your project as dependency.
Method 2: You can also add the jar dependency to your maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode
Replace Image
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("Polar bears.pptx");
//add an image to the image collection
String imagePath = "C:\\Users\\Administrator\\Desktop\\p1.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("ReplaceImage.pptx", FileFormat.PPTX_2013);
}
}
Enter fullscreen mode Exit fullscreen mode
暂无评论内容