Replacing image with text or image in a Word document is possible in Spire.Doc. We've already illustrated how to replace image with text, in this tutorial, we will show you how to replace a specified image with another image using Spire.Doc and C#.
Below is the original Word document before replacing image:
Code Snippet:
Step 1: Load the Word document.
Document document = new Document("Input.docx");
Step 2: Replace the image which title is "Figure 1" with new image.
//Loop through the paragraphs of the section foreach (Paragraph paragraph in document.Sections[0].Paragraphs) { //Loop through the child elements of paragraph foreach (DocumentObject docObj in paragraph.ChildObjects) { if (docObj.DocumentObjectType == DocumentObjectType.Picture) { DocPicture picture = docObj as DocPicture; if (picture.Title == "Figure 1") { //Replace the image picture.LoadImage(Image.FromFile("PinkRoses.jpg")); } } } }
Step 3: Save and close the document.
document.SaveToFile("ReplaceImage.docx"); document.Close();
The resultant document looks as follows:
Full code:
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace Replace_Image { class Program { static void Main(string[] args) { //Load the Word document Document document = new Document("Input.docx"); //Loop through the paragraphs of the section foreach (Paragraph paragraph in document.Sections[0].Paragraphs) { //Loop through the child elements of paragraph foreach (DocumentObject docObj in paragraph.ChildObjects) { if (docObj.DocumentObjectType == DocumentObjectType.Picture) { DocPicture picture = docObj as DocPicture; if (picture.Title == "Figure 1") { //Replace the image picture.LoadImage(Image.FromFile("PinkRoses.jpg")); } } } } //Save and close the document document.SaveToFile("ReplaceImage.docx"); document.Close(); } } }