All images are stored inside Shape nodes in a Document.
To extract all images or images having specific type from the document, follow these simple steps:
- Use the GetChildNodes method to select all Shape nodes.
- Iterate through resulting node collections.
- Check the Shape.HasImage boolean property.
- Extract image data using the ImageData property.
- Save image data to a file.
Example ExtractImagesToFiles
Shows how to extract images from a document and save them as files.
[C#]
[Test]
public void ExtractImagesToFiles()
{
Document doc = new Document(MyDir + "Image.SampleImages.doc");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true, false);
int imageIndex = 0;
foreach (Shape shape in shapes)
{
if (shape.HasImage)
{
string imageFileName = string.Format("Image.ExportImages.{0} Out.{1}", imageIndex, shape.ImageData.ImageType);
shape.ImageData.Save(MyDir + imageFileName);
imageIndex++;
}
}
}
[Visual Basic]
<Test> _
Public Sub ExtractImagesToFiles()
Dim doc As Document = New Document(MyDir & "Image.SampleImages.doc")
Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True, False)
Dim imageIndex As Integer = 0
For Each shape As Shape In shapes
If shape.HasImage Then
Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out.{1}", imageIndex, shape.ImageData.ImageType)
shape.ImageData.Save(MyDir & imageFileName)
imageIndex += 1
End If
Next shape
End Sub
[Java]
public void ExtractImagesToFiles() throws Exception
{
Document doc = new Document(getMyDir() + "Image.SampleImages.doc");
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true, false);
int imageIndex = 0;
for(int i = 0; i < shapes.getCount(); i++)
{
Shape shape = (Shape)shapes.get(i);
if (shape.hasImage())
{
String extension = ImageTypeToExtension(shape.getImageData().getImageType());
String imageFileName = MessageFormat.format("Image.ExportImages.{0} Out.{1}", imageIndex, extension);
shape.getImageData().save(getMyDir() + imageFileName);
imageIndex++;
}
}
}
private static String ImageTypeToExtension(int imageType) throws Exception
{
switch (imageType)
{
case ImageType.BMP:
return "bmp";
case ImageType.EMF:
return "emf";
case ImageType.JPEG:
return "jpeg";
case ImageType.PICT:
return "pict";
case ImageType.PNG:
return "png";
case ImageType.WMF:
return "wmf";
default:
throw new Exception("Unknown image type.");
}
}