Standard imghdr Library
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
- breaking The `imghdr` module was deprecated in Python 3.11 and completely removed from the Python standard library in Python 3.13 (PEP 594). Direct `import imghdr` will result in a `ModuleNotFoundError` in Python 3.13 and newer versions unless `standard-imghdr` is installed.
- deprecated The `standard-imghdr` library is a 'dead battery' redistribution of a removed standard library module. It is not actively developed for new features or significant improvements. The project explicitly states that it is intended for 'minimal compatibility work' only.
- gotcha On some Linux distributions, especially when trying to install system-wide without a virtual environment, `pip install standard-imghdr` might encounter issues or recommend `pipx`, which is not suitable for libraries.
Install
-
pip install standard-imghdr
Imports
- imghdr
import imghdr
Quickstart
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')