Archive

Posts Tagged ‘file command’

Determine the image type (JPG, GIF, PNG, etc.)

April 19, 2011 2 comments

Problem

You want to process an image but you want to verify if the user-specified input file is really an image.

Solution #1

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.

Solution #2

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

Command-line example:

$ 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()

Update (20131218)
Here is how to convert the return value of ms.file to a file extension:

FTYPES = {
    'JPEG' : 'jpg',
    'GIF' : 'gif',
    'PNG' : 'png',
}

def get_file_type(fname):
    ftype = ms.file(fname).split()[0]
    return FTYPES.get(ftype)

Solution #3
You can also use the module PIL to verify if the given file is an image. Refer to this thread for some examples.

Categories: python Tags: , ,
Design a site like this with WordPress.com
Get started