Replace Image with New Image in Word Using Java

This article will share how to replace an existing image in a Word document with a new image programmatically by using Free Spire.Doc for Java.

Installation
Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: Directly add the jar dependency to 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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Sample Code

import com.spire.doc.Document;
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("jellyfish.docx");

//Get the first section
Section section = doc.getSections().get(0);
Paragraph para = section.getParagraphs().get(1);

//Replace the first image in this section with new image
Object obj = para.getChildObjects().get(0);
if(obj instanceof DocPicture){
DocPicture pic = (DocPicture)obj;
pic.loadImage("C:\\Users\\Administrator\\Desktop\\img1.jpg");
}

/*//Replace all images
for(int i =0;i < section.getParagraphs().getCount();i++){
Object obj = section.getParagraphs().get(i).getChildObjects();
if(obj instanceof DocPicture){
DocPicture pic = (DocPicture)obj;
pic.loadImage("tp.png");
}
}*/

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

Before:

After:

Sharing Java Code