pythonimageidentificationimghdr

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


I am currently using PIL.

from PIL import Image

try:
    im = Image.open(filename)
    # 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 throw an OverflowError exception.

Is there someway I could include them as well?


Solution

  • A lot of times the first couple chars will be a magic number for various file formats. You could check for this in addition to your exception checking above.