Looping round to find matching image

Hi Support,

I have a directory of Word Documents some of which contain a specific inserted image. I want to iterate round the documents to find any which contain a specific reference image and then replace any found which a different image but I can’t find the right methods.

Can you help with a quick code sample and link to the right area of the documentation? I suppose if I see it done on a single document I can easily put it into a loop myself.

I am coding in a C# console app.

Many Thanks,
David.

Hi @daviddavis,
The following code snippet, allows you open a document, iterate over all the images in it and replace those with Jpeg extension with a custom Png image (you can use a different condition to replace the desired images you can found all the image metadata under the Shape property ImageData), and save the changes in a new document:

Document doc = new Document("C:\\Temp\\img.docx");

// Get all the nodes in the document.
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);

// Iterate over all the obtained nodes.
foreach (Shape shape in shapes)
{
    // Check if the Shape node is an image and if it is of type Jpeg.
    if (shape.HasImage && shape.ImageData.ImageType == ImageType.Jpeg)
    {
        // Replace the image.
        shape.ImageData.SetImage("C:\\Temp\\example.png");
    }
}

doc.Save("C:\\Temp\\out-img.docx");

If you need further guidance don’t doubt to ask, also you can found extra information about how to work with images following the link https://docs.aspose.com/words/net/working-with-images/.

Best!