Standard imghdr Library

3.13.0 · maintenance · verified Sun Apr 12

The `standard-imghdr` library is a redistribution of the `imghdr` module, which was formerly part of the Python standard library. It provides functionality to determine the type of an image file based on its header. Maintained by the `python-deadlib` project, this library serves as a compatibility layer for projects that relied on `imghdr` after its deprecation in Python 3.11 and subsequent removal in Python 3.13. The current version is 3.13.0 and it follows an infrequent release cadence focused on maintaining compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `imghdr.what()` to identify image types from both a filename and a byte stream. It creates temporary dummy JPEG and PNG files, identifies their types, and then cleans up the files.

import imghdr
import os

# Create a dummy JPEG file for demonstration
dummy_jpeg_data = b'\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xFF\xDB\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\x09\x09\x08\x0A\x0C\x14\x0D\x0C\x0B\x0B\x0C\x19\x12\x13\x0F\x14\x1D\x1A\x1F\x1E\x1D\x1A\x1C\x1C\x20\x24\x2E\x27\x20\x22\x2C\x23\x1C\x1C\x28\x37\x29\x2B\x30\x31\x30\x33\x31\x2F\x36\x2E\x37\x39\x3D\x3B\x3A\x32\x38\x37\x3D\x36\x36\x38\x37\x20\x20'
dummy_png_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\x0cIDATx\xda\xed\xc1\x01\x01\x00\x00\x00\xc2\xa0\xf7Om\x00\x00\x00\x00IEND\xaeB`\x82'

# Create temporary files
with open('test_image.jpg', 'wb') as f:
    f.write(dummy_jpeg_data)
with open('test_image.png', 'wb') as f:
    f.write(dummy_png_data)

# Determine image type by filename
image_type_jpg = imghdr.what('test_image.jpg')
print(f"Type of test_image.jpg: {image_type_jpg}")

image_type_png = imghdr.what('test_image.png')
print(f"Type of test_image.png: {image_type_png}")

# Determine image type from a byte stream
image_type_bytes = imghdr.what(None, h=dummy_jpeg_data)
print(f"Type of image from bytes: {image_type_bytes}")

# Clean up temporary files
os.remove('test_image.jpg')
os.remove('test_image.png')

view raw JSON →