Python: Check if uploaded file is jpg

前端 未结 5 1142
-上瘾入骨i
-上瘾入骨i 2020-12-05 03:20

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 F

5条回答
  •  自闭症患者
    2020-12-05 04:06

    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
    

提交回复
热议问题