Replace photo in "docx" with an image by resizing the image to the size of photo

Code : for (Shape shape : (Iterable) shapesToDelete){
BufferedImage originalImage = ImageIO.read(new File(filePath));
int height = (int) Math.round(shape.getHeight());
int width = (int) Math.round(shape.getWidth());
Image rescaled = originalImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(rescaled, 0, 0,width, height, null);
g.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( resizedImage, “png”, baos );
byte[] imageInByte = baos.toByteArray();
shape.getImageData().setImageBytes(imageInByte);
baos.flush(); ExpectedOutput.png (43.6 KB)
Output.png (41.9 KB)

    	}

I want to replace the photo in the shape with the image in the filePath.
I am getting the output as in Output.png and the expected output is in ExpectedOutput.png

@divya13

Thanks for your inquiry. To ensure a timely and accurate response, please attach the following resources here for testing:

  • Your input Word document.
  • Please attach the image that you want to insert in the shape.
  • Please attach the output Word file that shows the undesired behavior.
  • Please attach the expected output Word file that shows the desired behavior.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.

@tahir.manzoor . Thank you for the reply. Please find attached the requested documents.asposeword 2.zip (138.4 KB)

@divya13

Thanks for sharing the detail. In your case, we suggest you please insert the textbox/rectangle shape in your input document and use the following code example to achieve your requirement. We have attached the input document with this post for your kind reference. input.zip (22.5 KB)

Document doc = new Document(MyDir +"input.docx");
Shape shape = (Shape)doc.getChild(NodeType.SHAPE, 0, true);
shape.getImageData().setImage(MyDir + "image.png");

OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.setCompliance(OoxmlCompliance.ISO_29500_2008_STRICT);
doc.save(MyDir + "output.docx", ooxmlSaveOptions);