Fix Python – How to check if a file is a valid image file?

Question

Asked By – Sujoy

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 throws an OverflowError exception.

Is there someway I could include them as well?

Now we will see solution for issue: How to check if a file is a valid image file?


Answer

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.

This question is answered By – Brian R. Bondy

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0