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

16 投票
5 回答
23596 浏览
提问于 2025-04-11 17:46

我该怎么检查用户上传的文件是否是真正的jpg格式文件呢?(在Python的Google App Engine上)

到目前为止,我已经做到这些:

这个脚本通过HTML表单提交接收图片,然后用下面的代码处理:

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

我找到了一种叫mimetypes.guess_type的方法,但对我来说不太管用。

5 个回答

1

一个更通用的解决办法是使用Python来调用Unix系统的“file”命令。为了做到这一点,你需要安装一个叫做python-magic的包。下面是一个例子:

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

其实你不需要安装PIL这个库,因为Python自带的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

如果你有一个来自流的图片,可以像这样使用流选项:

image_type = imghdr.what(filename, incomming_image)

实际上在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()}

在上传控制器中:

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
37

如果你需要的不仅仅是查看文件的扩展名,一种方法是读取JPEG文件的头部信息,检查它是否符合有效的数据格式。这个格式是:

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

所以一个简单的识别方法可以是:

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

不过,这样的方法无法检测文件主体中的坏数据。如果你想要更可靠的检查,可以尝试用PIL来加载它。例如:

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

撰写回答