Python: Check if uploaded file is jpg

Federico Elles picture Federico Elles · Nov 5, 2008 · Viewed 19.6k times · Source

How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?

This is how far I got by now:

Script receives image via HTML Form Post and is processed by the following code

...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...

I found mimetypes.guess_type, but it does not work for me.

Answer

Brian picture Brian · Nov 5, 2008

If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is:

Start Marker  | JFIF Marker | Header Length | Identifier
0xff, 0xd8    | 0xff, 0xe0  |    2-bytes    | "JFIF\0"

so a quick recogniser would be:

def is_jpg(filename):
    data = open(filename,'rb').read(11)
    if data[:4] != '\xff\xd8\xff\xe0': return False
    if data[6:] != 'JFIF\0': return False
    return True

However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with PIL. eg:

from PIL import Image
def is_jpg(filename):
    try:
        i=Image.open(filename)
        return i.format =='JPEG'
    except IOError:
        return False