Determine the image type (JPG, PNG, etc.)
You want to process an image but you want to verify if the user-specified input file is really an image.
There is a standard module for this called imghdr. Its usage is very simple:
>>> import imghdr >>> imghdr.what('/tmp/bass.gif') 'gif'
The method checks the content of the file.
If you want a more general solution, i.e. you want to figure out the type of an arbitrary file, use the Python binding to the command “file“.
$ file lolcat.jpg lolcat.jpg: JPEG image data, JFIF standard 1.01
If you want to use it from Python, install the package “python-magic” (it’s in the Ubuntu repos). It comes with the following example:
import magic ms = magic.open(magic.MAGIC_NONE) ms.load() type = ms.file("/path/to/some/file") print type f = file("/path/to/some/file", "r") buffer = f.read(4096) f.close() type = ms.buffer(buffer) print type ms.close()
You can also use the module PIL to verify if the given file is an image. Refer to this thread for some examples.