Replace image in Word

Hi,

I am working on a document to replace an existing image with a new image. I found this post here Replace Image in Word document and tried the solution but it didn’t work out. I debugged it and found the shape part didn’t work with my document. I have attached the document, could you please take a look?

Thanks.

Hi Donghu,

Thanks for your inquiry. Images in Word documents are either represented by Shape
nodes or by DrawingML nodes when loading into Aspose.Words’ DOM. The
image found in your document is actually represented by
DrawingML node. Please read the members of DrawingML and Shape class from here:
https://reference.aspose.com/words/net/aspose.words.drawing/shape/
https://reference.aspose.com/words/net/aspose.words.drawing/shape/

Please use the following code examples to replace an existing image. Hope this helps you. Please let us know if you have any more queries.

Document doc = new Document(MyDir + "testImage.docx");
DrawingML shape = (DrawingML)doc.GetChild(NodeType.DrawingML, 0, true);
shape.ImageData.SetImage(MyDir + @"Aspose Logo.png");
doc.Save(MyDir + "Out.docx");

Document doc = new Document(MyDir + "testImage.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
DrawingML shape = (DrawingML)doc.GetChild(NodeType.DrawingML, 0, true);
builder.MoveTo(shape);
builder.InsertImage(MyDir + @"Aspose Logo.png");
shape.Remove();
doc.Save(MyDir + "Out.docx");

It’s working. Thanks so much.

Hi Donghu,

Thanks for your feedback. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.