Working with Images
Aspose.Words allows users to work with images in a very flexible way. In this article, you can explore only some of the possibilities of working with images.
How to Extract Images from a Document
All images are stored inside Shape nodes in a Document. To extract all images or images having a specific type from the document, follow these steps:
- Use the GetChildNodes method to select all Shape nodes.
- Iterate through resulting node collections.
- Check the HasImage boolean property.
- Extract image data using the ImageData property.
- Save image data to a file.
The following code example shows how to extract images from a document and save them as files:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
// The path to the documents directories. | |
System::String inputDataDir = GetInputDataDir_WorkingWithImages(); | |
System::String outputDataDir = GetOutputDataDir_WorkingWithImages(); | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Image.SampleImages.doc"); | |
System::SharedPtr<NodeCollection> shapes = doc->GetChildNodes(NodeType::Shape, true); | |
int32_t imageIndex = 0; | |
for (System::SharedPtr<Shape> shape : System::IterateOver<System::SharedPtr<Shape>>(shapes)) | |
{ | |
if (shape->get_HasImage()) | |
{ | |
System::String imageFileName = System::String::Format(u"Image.ExportImages.{0}.{1}", imageIndex, FileFormatUtil::ImageTypeToExtension(shape->get_ImageData()->get_ImageType())); | |
System::String imagePath = outputDataDir + imageFileName; | |
shape->get_ImageData()->Save(imagePath); | |
std::cout << "Image saved at " << imagePath.ToUtf8String() << std::endl; | |
imageIndex++; | |
} | |
} |
Saving Images as WMF
Aspose.Words provides functionality to save all the available images in a document to WMF format while converting DOCX to RTF.
The following code example shows how to save images as WMF with RTF save options:
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc"); | |
System::SharedPtr<RtfSaveOptions> options = System::MakeObject<RtfSaveOptions>(); | |
options->set_SaveImagesAsWmf(true); | |
doc->Save(outputDataDir + u"WorkingWithRtfSaveOptions.SavingImagesAsWmf.rtf", options); |