Python:检查上传的文件是否为jpg
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/266648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Check if uploaded file is jpg
提问by Federico Elles
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?
如何在 Python (Google App Engine) 中检查用户上传的文件是否是真正的 jpg 文件?
This is how far I got by now:
这是我现在有多远:
Script receives image via HTML Form Post and is processed by the following code
脚本通过 HTML Form Post 接收图片并由以下代码处理
...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...
I found mimetypes.guess_type, but it does not work for me.
我找到了 mimetypes.guess_type,但它对我不起作用。
回答by Brian
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:
如果您需要的不仅仅是查看扩展名,一种方法是读取 JPEG 标头,并检查它是否与有效数据匹配。其格式为:
Start Marker | JFIF Marker | Header Length | Identifier
0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIFdef is_jpg(filename):
data = open(filename,'rb').read(11)
if data[:4] != '\xff\xd8\xff\xe0': return False
if data[6:] != 'JFIFfrom PIL import Image
def is_jpg(filename):
try:
i=Image.open(filename)
return i.format =='JPEG'
except IOError:
return False
': return False
return True
"
so a quick recogniser would be:
所以一个快速的识别器是:
import imghdr
image_type = imghdr.what(filename)
if not image_type:
print "error"
else:
print image_type
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:
但是,这不会捕获正文中的任何不良数据。如果您想要更强大的检查,您可以尝试使用PIL加载它。例如:
image_type = imghdr.what(filename, incomming_image)
回答by Brian
No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage.
无需为此使用和安装 PIL 库,有适合这种用法的 imghdr 标准模块。
See http://docs.python.org/library/imghdr.html
见http://docs.python.org/library/imghdr.html
${h.form(h.url_for(action="save_image"), multipart=True)}
Upload file: ${h.file("upload_file")} <br />
${h.submit("Submit", "Submit")}
${h.end_form()}
As you have an image from a stream you may use the stream option probably like this :
由于您有来自流的图像,您可以使用流选项,可能如下所示:
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
Actualy this works for me in Pylons (even if i have not finished everything) : in the Mako template :
实际上,这在 Pylons 中对我有用(即使我还没有完成所有事情):在 Mako 模板中:
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()
in the upload controler :
在上传控制器中:
def is_jpg(filename):
data = open("uploads/" + filename,'rb').read(11)
if (data[:3] == "\xff\xd8\xff"):
return True
elif (data[6:] == 'JFIF>>> import Image
>>> im = Image.open("lena.ppm")
>>> print im.format, im.size, im.mode
'):
return True
else:
return False
回答by Jabba
A more general solution is to use the Python binding to the Unix "file" command. For this, install the package python-magic. Example:
更通用的解决方案是使用 Python 绑定到 Unix“文件”命令。为此,请安装包 python-magic。例子:
##代码##回答by Christian Papathanasiou
The last byte of the JPEG file specification seems to vary beyond just e0. Capturing the first three is 'good enough' of a heuristic signature to reliably identify whether the file is a jpeg. Please see below modified proposal:
JPEG 文件规范的最后一个字节似乎不仅仅是 e0。捕获前三个“足够好”的启发式签名可以可靠地识别文件是否为 jpeg。请参阅以下修改后的提案:
##代码##