Determine the type of an image in Python?

In this section, we are going to see how to determine the type of image file programmatically using Python. Consider a situation where you have hundreds of image files in a directory and want to filter specific image formats like JPEG, PNG, or GIF.

Python provides the imghdr library to determine the type of an image contained in a file or byte stream.

Installation

The imghdr module is a standard library package that comes with Python 3.6 and higher installations. However, if you need to install it separately, run the following command ?

pip install imghdr

To verify the installation, import the module in your Python shell ?

import imghdr
print("imghdr module imported successfully!")
imghdr module imported successfully!

Syntax

The imghdr package defines the following function ?

imghdr.what(filename[, h])

Parameters

  • filename: Path to the image file to test. Returns a string describing the image type.

  • h (optional): If provided, filename is ignored and h is assumed to contain the byte stream to test.

Supported Image Formats

Below are the image formats recognized by the imghdr package ?

Return Value Image Format
'jpeg' JPEG data in JFIF or Exif formats
'png' Portable Network Graphics
'gif' GIF 87a and 89a Files
'bmp' BMP files
'tiff' TIFF Files
'pbm' Portable Bitmap Files
'pgm' Portable Graymap Files
'ppm' Portable Pixmap Files
'rgb' SGI ImgLib Files
'rast' Sun Raster Files
'xbm' X Bitmap Files

Basic Example

Let's create a simple example to determine image types ?

import imghdr

# Create a sample image data (PNG signature)
png_signature = b'\x89PNG\r\n\x1a\n'

# Test with byte stream
image_type = imghdr.what(None, png_signature)
print(f"Image type from byte stream: {image_type}")

# You can also test with actual files
# image_type = imghdr.what('sample.jpg')
# print(f"Image type: {image_type}")
Image type from byte stream: png

Practical Implementation

Here's a practical function to identify and organize image files by their actual format ?

import imghdr
import os

def identify_image_type(image_path):
    """
    Identify the actual image type regardless of file extension
    """
    try:
        file_type = imghdr.what(image_path)
        if file_type:
            print(f"File: {os.path.basename(image_path)}")
            print(f"Detected type: {file_type}")
            return file_type
        else:
            print(f"Unknown or invalid image format: {image_path}")
            return None
    except Exception as e:
        print(f"Error processing {image_path}: {e}")
        return None

# Example usage
sample_files = ['image.jpg', 'photo.png', 'graphic.gif']

for filename in sample_files:
    print(f"Testing: {filename}")
    # In real scenario, you would pass actual file paths
    print("---")
Testing: image.jpg
---
Testing: photo.png
---
Testing: graphic.gif
---

Filtering Images by Type

Here's how to filter specific image types from a directory ?

import imghdr
import os

def filter_images_by_type(directory, target_type='jpeg'):
    """
    Filter images by their actual type (not extension)
    """
    target_images = []
    
    # Simulate directory listing
    sample_files = ['photo1.jpg', 'image2.png', 'graphic.gif', 'document.pdf']
    
    for filename in sample_files:
        filepath = os.path.join(directory, filename)
        
        # In real implementation, you would check if file exists
        # and use actual file path with imghdr.what(filepath)
        
        # Simulating different file types for demonstration
        if filename.endswith('.jpg'):
            detected_type = 'jpeg'
        elif filename.endswith('.png'):
            detected_type = 'png'
        elif filename.endswith('.gif'):
            detected_type = 'gif'
        else:
            detected_type = None
            
        if detected_type == target_type:
            target_images.append(filename)
            print(f"Found {target_type}: {filename}")
    
    return target_images

# Find all JPEG images
jpeg_files = filter_images_by_type('/path/to/images', 'jpeg')
print(f"\nTotal JPEG files found: {len(jpeg_files)}")
Found jpeg: photo1.jpg
Total JPEG files found: 1

Conclusion

The imghdr module provides a reliable way to determine actual image formats regardless of file extensions. Use imghdr.what() to identify image types programmatically and build robust image processing applications.

Updated on: 2026-03-25T05:40:13+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements