Replace Image with New Image in Word in Java

This article demonstrates how to replace an existing image in a Word document with a new image using Spire.Doc for Java.

Below is the screenshot of the original Word document before replacing image:

Replace Image with New Image in Word in Java

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;

public class ReplaceImages {
    public static void main(String[] args){
        //Load the Word document
        Document doc = new Document();
        doc.loadFromFile("Images.docx");

        //Get the first section
        Section section = doc.getSections().get(0);

        //Loop through the paragraphs in the section
        for (Paragraph para:(Iterable) section.getParagraphs()
             ) {
            //Loop through the child object in the paragraph
            for (DocumentObject obj:(Iterable) para.getChildObjects()
                 ) {
                //Replace image with new image
                if(obj instanceof DocPicture){
                    DocPicture pic = (DocPicture)obj;
                    pic.loadImage("Hydrangeas.jpg");
                }
            }
        }

        //Save the resultant document
        doc.saveToFile("ReplaceWithImage.docx", FileFormat.Docx_2013);
    }
}

Output:

Replace Image with New Image in Word in Java