Determine the type of an image using Python (imghdr)

The imghdr module in Python's standard library determines the type of image contained in a file or byte stream. There is only one function defined in imghdr module

imghdr.what(filename, h=None):

This function tests the image data contained in the file and returns a string describing the image type. The function also accepts h parameter. If given the filename is ignored and h is treated as the byte stream to test.

The imghdr module recognizes the following image types

valueimage format
'rgb'SGI ImgLib Files
'gif'GIF 87a and 89a Files
'pbm'Portable Bitmap Files
pgm'Portable Graymap Files
'ppm'Portable Pixmap Files
'tiff'TIFF Files
'rast'Sun Raster Files
'xbm'X Bitmap Files
'jpeg'JPEG data in JFIF or Exif formats
'bmp'BMP files
'png'Portable Network Graphics
'webp'WebP files
'exr'OpenEXR Files


>>> import imghdr
>>> imghdr.what('bass.gif')
>>> imghdr.what('polar.png')
>>> imghdr.what('test.jpg')