How to check if a file is a valid image file?

I am currently using PIL.

from PIL import Image
    # do stuff
except IOError:
    # filename not an image file

However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception.

Is there someway I could include them as well?


I have just found the builtin imghdr module. From python documentation:

The imghdr module determines the type
of image contained in a file or byte

This is how it works:

>>> import imghdr
>>> imghdr.what('/tmp/bass')

Using a module is much better than reimplementing similar functionality

Source : Link , Question Author : Sujoy , Answer Author : Nadia Alramli

Leave a Comment