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

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

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.

About these ads
Categories: python Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 74 other followers

%d bloggers like this: