Python PIL图像验证返回无 [英] Python PIL image Verify returns None
问题描述
我正在开发一种工具,该工具可从API检索JPG并对其进行处理.图片来源无法信任,我想测试图片是否为有效的JPG(这是唯一允许的图片类型).
I am developing a tool which retrieves a JPG from an API and processes it. The source of the image cannot be trusted and I want to test if the image is a valid JPG (which is the only image type allowed).
我遇到了无法修复的PIL错误.下面是我的代码:
I encountered an error with PIL that I am unable to fix. Below is my code:
image = StringIO(base64.b64decode(download['file']))
img = Image.open(image)
if img.verify():
print 'Valid image'
else:
print 'Invalid image'
但是,似乎img.verify()返回None.我可以在打开的图像上调用其他函数,例如返回大小的img.size().尝试调试代码时,我得到以下输出:
However, it seems that img.verify() returns None. I can call other functions on the open image like img.size() which returns the size. I get the following output when I try to debug the code:
img = Image.open(image)
print img
print img.size()
print img.verify()
[2018-01-09 20:56:43,715: WARNING/Worker-1] <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2577x1715 at 0x7F16E17DC9D0>
[2018-01-09 20:56:43,716: WARNING/Worker-1] (2577, 1715)
[2018-01-09 20:56:43,716: WARNING/Worker-1] None
有人遇到过同样的问题吗?
Has someone encountered the same issue?
推荐答案
根据文档用于验证的PIL文档)在图像出现问题时引发异常,否则不执行任何操作.
According to the docs, Image#verify (or the PIL docs for verify) raises an exception if there is a problem with the image and does nothing otherwise.
要使用#verify
,您可能需要这样的东西:
To use #verify
, you probably want something like this:
image = StringIO(base64.b64decode(download['file']))
img = Image.open(image)
try:
img.verify()
print('Valid image')
except Exception:
print('Invalid image')
Additionally, you might want to also check that the image is actually a JPG by looking at the image format:
if img.format == 'JPEG':
print('JPEG image')
else:
print('Invalid image type')
这篇关于Python PIL图像验证返回无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!