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

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


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 stream.

This is how it works:

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

Using a module is much better than reimplementing similar functionality


In addition to what Brian is suggesting you could use PIL's verify method to check if the file is broken.

im.verify()

Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file. Attributes


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.