DEV Community

Leon Davis
Leon Davis

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

ExtractedImages/
├── Image-1.png
├── Image-2.png
└── Image-3.png
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)