Python Imghdr Module
The imghdr module determines the type of image contained in a file or byte stream.
Note: The imghdr module is deprecated as of Python 3.11 and was removed in Python 3.13. It is recommended to use external libraries like filetype, puremagic, or python-magic for file type detection.
Importing the Module
import imghdr
Determining Image Type
imghdr.what()
The imghdr.what() function tests the image data contained in the file named by filename, and returns a string describing the image type. If optional h is provided, the filename is ignored and h is assumed to contain the byte stream to test.
import imghdr
filename = 'image.png'
image_type = imghdr.what(filename)
if image_type:
print(f"Image type: {image_type}")
else:
print("Could not determine image type.")
Using Byte Stream
You can also pass the image data directly as bytes.
import imghdr
with open('image.jpeg', 'rb') as f:
data = f.read()
print(imghdr.what(None, data))
Supported Types
The following image types are recognized:
'rgb','gif','pbm','pgm','ppm','tiff','rast','xbm','jpeg','bmp','png','webp','exr'