Skip to main content

How to Extract Images from Word Documents with Python

Word files may contain screenshots, product photos, diagrams, logos, and other embedded images. When these images need to be reused separately, saving them one by one from Microsoft Word is inefficient, especially when a document contains dozens of pictures.

This article shows how to extract images from Word documents with Python and save them as separate image files.


Prerequisites

Make sure Python is installed on your computer, then install the required package:

pip install Spire.Doc

Step 1: Load the Word Document in Python

First, import the required modules and load the document with the LoadFromFile method:

import queue
from spire.doc import *
from spire.doc.common import *

doc = Document()
doc.LoadFromFile("Sample.docx")

The document is now available for traversing its internal objects.

Step 2: Find Images in the Word Document

Images in a Word document are represented as DocPicture objects.

Because pictures may appear inside different document objects, you can use a queue to traverse the document structure and identify objects whose type is DocumentObjectType.Picture.

nodes = queue.Queue()
nodes.put(doc)

images = []

while not nodes.empty():
    node = nodes.get()

    for i in range(node.ChildObjects.Count):
        child = node.ChildObjects.get_Item(i)

        if child.DocumentObjectType == DocumentObjectType.Picture:
            picture = child if isinstance(child, DocPicture) else None

            if picture is not None:
                images.append(picture.ImageBytes)

        elif isinstance(child, ICompositeObject):
            nodes.put(child)

When a picture is found, its binary image data is retrieved through the ImageBytes property and stored in the images list.

Step 3: Save the Extracted Word Images

After collecting the image data, write each image to a separate file:

import os

output_folder = "ExtractedImages"
os.makedirs(output_folder, exist_ok=True)

for i, image_data in enumerate(images, start=1):
    output_path = os.path.join(
        output_folder,
        f"Image-{i}.png"
    )

    with open(output_path, "wb") as image_file:
        image_file.write(image_data)

For a document containing three pictures, the output folder will look like this:

ExtractedImages/
├── Image-1.png
├── Image-2.png
└── Image-3.png

Full Python Code to Extract Images from Word

Here is the complete example:

import os
import queue
from spire.doc import *
from spire.doc.common import *

input_file = "Sample.docx"
output_folder = "ExtractedImages"

os.makedirs(output_folder, exist_ok=True)

# Load the Word document
doc = Document()
doc.LoadFromFile(input_file)

# Traverse the document objects
nodes = queue.Queue()
nodes.put(doc)

images = []

while not nodes.empty():
    node = nodes.get()

    for i in range(node.ChildObjects.Count):
        child = node.ChildObjects.get_Item(i)

        # Get embedded pictures
        if child.DocumentObjectType == DocumentObjectType.Picture:
            picture = child if isinstance(child, DocPicture) else None

            if picture is not None:
                images.append(picture.ImageBytes)

        # Continue traversing nested objects
        elif isinstance(child, ICompositeObject):
            nodes.put(child)

# Save the extracted images
for i, image_data in enumerate(images, start=1):
    output_path = os.path.join(
        output_folder,
        f"Image-{i}.png"
    )

    with open(output_path, "wb") as image_file:
        image_file.write(image_data)

doc.Close()

The script scans the document, collects embedded pictures, and saves them to the ExtractedImages folder.

Extract Images from Multiple Word Documents with Python

If you have multiple Word files, the same extraction logic can be placed inside a function and applied to every .docx file in a folder.

For example:

for filename in os.listdir("WordFiles"):
    if filename.lower().endswith(".docx"):
        input_path = os.path.join("WordFiles", filename)

        # Run the image extraction logic for each document

For batch processing, it is usually better to create a separate output folder for each source document so images with the same file names do not overwrite one another.

Things to Know When Extracting Images from Word

  • The example extracts objects represented as DocPicture.
  • Charts, SmartArt, shapes, OLE objects, and other graphical elements may use different Word object types and are not necessarily extracted by this code.
  • The example saves the extracted image data with .png file names. If preserving the original image format is important, the source image format should be identified before assigning the output extension.
  • Always call Close() after processing the document to release its resources.

Conclusion

Extracting images from Word with Python is useful when documents contain many embedded pictures that need to be reused, archived, or processed separately.

By traversing the Word document objects, identifying DocPicture instances, and retrieving their image data, you can automate the extraction instead of saving each image manually. 

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...