all Python 3until 3.13Removed from the standard libraryterm
imghdr
removed modules
Detected the image type from the first bytes of a file. Removed in Python 3.13 — check the byte signature yourself or use Pillow or filetype.
Syntax
import imghdr # до 3.13
imghdr.what(file) or imghdr.what(None, h=data) returned 'png', 'jpeg', 'gif' and a dozen other names based on the magic bytes at the start. PEP 594 dropped it: the format list was outdated (no newer WebP variants, AVIF, HEIC) and nobody maintained it. How to port: read the first bytes of the file and compare them with signatures via startswith — b'\x89PNG\r\n\x1a\n' for PNG, b'\xff\xd8\xff' for JPEG, b'GIF8' for GIF. If you open the image anyway, PIL.Image.open(f).format from Pillow names the format and validates the file. The filetype and puremagic libraries know hundreds of signatures; the standard-imghdr package restores the old module.
Examples
# Python 3.13+
try:
import imghdr
except ModuleNotFoundError as e:
print(type(e).__name__) # → ModuleNotFoundError
# Python 3.13+
SIGNATURES = {b'\x89PNG\r\n\x1a\n': 'png', b'\xff\xd8\xff': 'jpeg', b'GIF8': 'gif'}
def what(head):
for magic, kind in SIGNATURES.items():
if head.startswith(magic):
return kind
return None
print(what(b'\x89PNG\r\n\x1a\n' + bytes(24))) # → png
print(what(b'hello')) # → None
import imghdr
print(imghdr.what(None, h=b'\x89PNG\r\n\x1a\n' + bytes(24))) # → png
print(imghdr.what(None, h=b'hello')) # → None
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy