Extract images from document

View as MarkdownMarkdown

Set up your AI agent

Give your coding agent live access to the GroupDocs documentation and API reference through the GroupDocs Docs MCP server — no install, no API key. Learn more

claude mcp add --transport http groupdocs-docs https://docs.groupdocs.com/mcp

Also process documents locally

The GroupDocs.Parser MCP server lets your agent work with files on your machine; they are never uploaded. It runs in Docker: replace /path/to/documents with the folder it may use.

claude mcp add groupdocs-parser -- docker run --rm -i -v /path/to/documents:/data ghcr.io/groupdocs-parser/parser-net-mcp:latest
Folders, licensing and more →

GroupDocs.Parser provides functionality to extract images from various document formats including PDF, Word, Excel, PowerPoint, and more.

Prerequisites

  • GroupDocs.Parser for Python via .NET installed
  • Sample documents containing images
  • Write access to save extracted images (optional)

Extract images from document

To extract all images from a document:

from groupdocs.parser import Parser

# Create an instance of Parser class
with Parser("./sample.pdf") as parser:
    # Extract images
    images = parser.get_images()
    
    # Check if image extraction is supported
    if images is None:
        print("Image extraction isn't supported")
    elif not images:
        print("No images found")
    else:
        # Iterate over images
        for idx, image in enumerate(images):
            # Print image information
            print(f"Image {idx + 1}:")
            print(f"  Page: {image.page.index + 1}")
            print(f"  Type: {image.file_type}")
            print(f"  Size: {image.rectangle.size.width}x{image.rectangle.size.height}")
            print(f"  Position: ({image.rectangle.left}, {image.rectangle.top})")

The following sample file is used in this example: sample.pdf

Image 1:
  Page: 1
  Type: JPEG Image(.jpeg)
  Size: 150x45
  Position: (40, 70.99999999593751)
Image 2:
  Page: 1
  Type: JPEG Image(.jpeg)
  Size: 375x234
  Position: (110, 383.9999999959375)
[TRUNCATED]

Download full output

Expected behavior: Returns a collection of PageImageArea objects representing all images found in the document, or None if image extraction is not supported.

Save extracted images to files

To save extracted images to disk:

from groupdocs.parser import Parser
import os

# Create output directory
output_dir = "extracted_images"
os.makedirs(output_dir, exist_ok=True)

# Create an instance of Parser class
with Parser("./sample.docx") as parser:
    # Extract images
    images = parser.get_images()
    
    if images is None:
        print("Image extraction isn't supported")
    elif not images:
        print("No images found")
    else:
        # Iterate over images and save them
        for idx, image in enumerate(images):
            # Get file extension based on image type
            extension = image.file_type.extension
            
            # Generate filename
            filename = f"image_{idx + 1}{extension}"
            filepath = os.path.join(output_dir, filename)
            
            # Save image to file
            image.save(filepath)
            print(f"Saved: {filepath}")

The following sample file is used in this example: sample.docx

extracted_images/image_1.png (4 KB)
extracted_images/image_2.jpeg (176 KB)
extracted_images/image_3.jpeg (136 KB)

Download full output

Expected behavior: Saves each extracted image to a separate file with the appropriate file extension (.png, .jpg, .gif, etc.).

Extract images with metadata

To extract images along with detailed metadata:

from groupdocs.parser import Parser

# Create an instance of Parser class
with Parser("./sample.pptx") as parser:
    # Check if image extraction is supported
    if not parser.features.images:
        print("Document doesn't support image extraction")
    else:
        # Extract images
        images = parser.get_images()
    
        if images:
            print(f"Found {len(images)} images\n")

            for idx, image in enumerate(images):
                print(f"Image {idx + 1}:")
                print(f"  Page: {image.page.index + 1}")
                print(f"  Format: {image.file_type}")
                print(f"  Rotation: {image.rotation} degrees")
                print(f"  Rectangle: {image.rectangle}")
                print(f"  Width: {image.rectangle.size.width}")
                print(f"  Height: {image.rectangle.size.height}")
                print()
        else:
            print("No images found")

The following sample file is used in this example: sample.pptx

Found 4 images

Image 1:
  Page: 1
  Format: Portable Network Graphic(.png)
  Rotation: 0 degrees
  Rectangle: (30; 20) (150; 45)
  Width: 150
  Height: 45

[TRUNCATED]

Download full output

Expected behavior: Displays comprehensive information about each image including position, size, format, and rotation angle.

Get image stream

To work with image data as a stream:

from groupdocs.parser import Parser
from groupdocs.parser.options import ImageOptions, ImageFormat

# Create an instance of Parser class
with Parser("./sample.pdf") as parser:
    # Extract images
    images = parser.get_images()
    
    if images:
        for idx, image in enumerate(images):
            # Get image stream (a .NET MemoryStream)
            image_stream = image.get_image_stream()
            
            # Read image data: to_array() returns the stream content as bytes
            image_data = image_stream.to_array()
            print(f"Image {idx + 1}: {len(image_data)} bytes, format: {image.file_type}")
            
            # Optionally convert to PNG
            png_options = ImageOptions(ImageFormat.PNG)
            png_stream = image.get_image_stream(png_options)
            png_data = png_stream.to_array()
            print(f"  Converted to PNG: {len(png_data)} bytes")
    else:
        print("No images found")

The following sample file is used in this example: sample.pdf

Image 1: 10365 bytes, format: JPEG Image(.jpeg)
  Converted to PNG: 55430 bytes
Image 2: 90027 bytes, format: JPEG Image(.jpeg)
  Converted to PNG: 633711 bytes
Image 3: 125180 bytes, format: JPEG Image(.jpeg)
  Converted to PNG: 837256 bytes
Image 4: 163435 bytes, format: JPEG Image(.jpeg)
  Converted to PNG: 1186275 bytes
Image 5: 94989 bytes, format: JPEG Image(.jpeg)
  Converted to PNG: 928726 bytes

Download full output

Expected behavior: Provides access to raw image data as a stream, with optional format conversion.

Convert images during extraction

To convert images to a specific format during extraction:

from groupdocs.parser import Parser
from groupdocs.parser.options import ImageOptions, ImageFormat
import os

# Create output directory
output_dir = "converted_images"
os.makedirs(output_dir, exist_ok=True)

# Create an instance of Parser class
with Parser("./sample.pdf") as parser:
    # Extract images
    images = parser.get_images()
    
    if images:
        # Create image options for PNG format
        png_options = ImageOptions(ImageFormat.PNG)
        
        for idx, image in enumerate(images):
            # Save image as PNG (regardless of original format)
            filename = f"image_{idx + 1}.png"
            filepath = os.path.join(output_dir, filename)
            
            # Save with conversion
            image.save(filepath, png_options)
            print(f"Saved as PNG: {filepath}")
    else:
        print("No images found")

The following sample file is used in this example: sample.pdf

converted_images/image_1.png (54 KB)
converted_images/image_2.png (619 KB)
converted_images/image_3.png (818 KB)
converted_images/image_4.png (1158 KB)
converted_images/image_5.png (907 KB)

Download full output

Expected behavior: All extracted images are converted to PNG format before saving, regardless of their original format.

Batch image extraction

Extract images from multiple documents:

from groupdocs.parser import Parser
import os
from pathlib import Path

def extract_images_from_directory(input_dir, output_dir):
    """
    Extract images from all documents in a directory.
    """
    os.makedirs(output_dir, exist_ok=True)
    
    # Supported document extensions
    extensions = ['.pdf', '.docx', '.doc', '.xlsx', '.pptx', '.ppt']
    
    for file_path in sorted(Path(input_dir).rglob('*')):
        if file_path.suffix.lower() in extensions:
            print(f"\nProcessing: {file_path.name}")
            
            try:
                with Parser(str(file_path)) as parser:
                    images = parser.get_images()
                    
                    if images is None:
                        print(f"  Image extraction not supported")
                        continue
                    
                    # Create subdirectory for this document
                    doc_output_dir = os.path.join(output_dir, file_path.stem)
                    os.makedirs(doc_output_dir, exist_ok=True)
                    
                    # Save images
                    image_count = 0
                    for idx, image in enumerate(images):
                        filename = f"image_{idx + 1}{image.file_type.extension}"
                        filepath = os.path.join(doc_output_dir, filename)
                        image.save(filepath)
                        image_count += 1
                    
                    print(f"  Extracted {image_count} images")
                    
            except Exception as e:
                print(f"  Error: {e}")

# Usage
extract_images_from_directory("documents", "extracted_images")

The following sample files are used in this example: annual-report.pdf, product-catalog.pptx, service-agreement.docx

extracted_images/annual-report/image_1.jpeg (10 KB)
extracted_images/annual-report/image_2.jpeg (88 KB)
extracted_images/annual-report/image_3.jpeg (122 KB)
extracted_images/annual-report/image_4.jpeg (160 KB)
extracted_images/annual-report/image_5.jpeg (93 KB)
extracted_images/product-catalog/image_1.png (4 KB)
extracted_images/product-catalog/image_2.jpeg (136 KB)
extracted_images/product-catalog/image_3.jpeg (75 KB)
extracted_images/product-catalog/image_4.jpeg (105 KB)
extracted_images/service-agreement/image_1.png (4 KB)
[TRUNCATED] (12 files total)

Download full output

Notes

  • The get_images() method returns None if image extraction is not supported for the document format
  • Always check parser.features.images before attempting to extract images
  • Supported output formats: BMP, GIF, JPEG, PNG, WebP
  • Images are extracted with their original quality and resolution
  • The rotation property indicates the image rotation angle (0, 90, 180, or 270 degrees)
  • Use get_image_stream() for memory-efficient processing of large images