'Replacing an image using Apache POI is not working

I want to replace an existing image present in a slide of a PPT using Apache POI. But there is some difficulty to achieve this. Can anyone suggest how to approach the problem since I am quite new to this and I could not find any articles that could help me?



Solution 1:[1]

Aspose.Slides for Java makes it easy to replace an image with another in a PowerPoint presentation. The following code example shows you how to do this:

// Load a presentation file.
var presentation = new Presentation("input.pptx");

// Add an image to presentation resources.
var imageData = Files.readAllBytes(Paths.get("image.png"));
var newImage = presentation.getImages().addImage(imageData);

// Let's the first shape on the first slide is a picture frame.
var firstSlide = presentation.getSlides().get_Item(0);
var pictureFrame = (IPictureFrame) firstSlide.getShapes().get_Item(0);

// Replace an image with the new one.
pictureFrame.getPictureFormat().getPicture().setImage(newImage);

// Save the presentation.
presentation.save("output.pptx", SaveFormat.Pptx);

presentation.dispose();

Alternatively, you can use Aspose.Slides Cloud SDK for Java that provides a REST-based API for managing presentations. The code example below shows you how to update an image in a presentation using Aspose.Slides Cloud:

var slidesApi = new SlidesApi("my_client_id", "my_client_secret");

var fileName = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;

// Get image data as a Base64 string.
var imageData = Files.readAllBytes(Paths.get("image.png"));
var imageBase64String = Base64.getEncoder().encodeToString(imageData);

// Get a picture frame.
var pictureFrame = (PictureFrame)slidesApi.getShape(fileName, slideIndex, shapeIndex, null, null, null);

// Update the image data.
pictureFrame.setPictureFillFormat(new PictureFill());
pictureFrame.getPictureFillFormat().setBase64Data(imageBase64String);

// Update the picture frame.
slidesApi.updateShape(fileName, slideIndex, shapeIndex, pictureFrame, null, null, null);

I work as a Support Developer at Aspose.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrey Potapov