Python:检查上传的文件是否为jpg

Fed*_*les 15 python google-app-engine mime image image-processing

如何检查用户上传的文件是否是Python(Google App Engine)中的真实jpg文件?

这是我现在走了多远:

脚本通过HTML Form Post接收图像,并由以下代码处理

...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...
Run Code Online (Sandbox Code Playgroud)

我找到了mimetypes.guess_type,但它对我不起作用.

Bri*_*ian 36

如果您需要的不仅仅是查看扩展,一种方法是读取JPEG标头,并检查它是否与有效数据匹配.格式为:

Start Marker  | JFIF Marker | Header Length | Identifier
0xff, 0xd8    | 0xff, 0xe0  |    2-bytes    | "JFIF\0"
Run Code Online (Sandbox Code Playgroud)

所以一个快速识别器将是:

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
Run Code Online (Sandbox Code Playgroud)

然而,这不会捕获身体中的任何不良数据.如果您想要更健壮的检查,可以尝试使用PIL加载它.例如:

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


小智 34

不需要为此使用和安装PIL lybrary,imghdr标准模块完全符合这种用法.

请参见http://docs.python.org/library/imghdr.html

import imghdr

image_type = imghdr.what(filename)
if not image_type:
    print "error"
else:
    print image_type
Run Code Online (Sandbox Code Playgroud)

由于您有一个来自流的图像,您可以使用stream选项,如下所示:

image_type = imghdr.what(filename, incomming_image)
Run Code Online (Sandbox Code Playgroud)

Actualy这对我在Pylons中起作用(即使我还没有完成所有事情):在Mako模板中:

${h.form(h.url_for(action="save_image"), multipart=True)}
Upload file: ${h.file("upload_file")} <br />
${h.submit("Submit", "Submit")}
${h.end_form()}
Run Code Online (Sandbox Code Playgroud)

在上传控制器中:

def save_image(self):
    upload_file = request.POST["upload_file"]
    image_type = imghdr.what(upload_file.filename, upload_file.value)
    if not image_type:
        return "error"
    else:
        return image_type
Run Code Online (Sandbox Code Playgroud)

  • +1为imghdr作为标准模块 (3认同)