Python PIL图像验证返回无

nob*_*ody 5 python python-imaging-library pillow

我正在开发一种从API检索JPG并对其进行处理的工具。无法信任图片的来源,我想测试图片是否为有效的JPG(这是允许的唯一图片类型)。

我遇到了无法修复的PIL错误。下面是我的代码:

image = StringIO(base64.b64decode(download['file']))
img = Image.open(image)
if img.verify():
    print 'Valid image'
else:
    print 'Invalid image'
Run Code Online (Sandbox Code Playgroud)

但是,似乎img.verify()返回None。我可以在打开的图像上调用其他函数,例如返回大小的img.size()。当我尝试调试代码时,得到以下输出:

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

有人遇到过同样的问题吗?

sup*_*654 8

根据该文档,图片#验证(或用于验证PIL文档)是否存在与图像问题,什么也不做,否则会引发异常。

要使用#verify,您可能想要这样的东西:

image = StringIO(base64.b64decode(download['file']))
img = Image.open(image)
try:
    img.verify()
    print('Valid image')
except Exception:
    print('Invalid image')
Run Code Online (Sandbox Code Playgroud)

此外,您可能还希望通过查看图像格式来检查图像是否实际上是JPG :

if img.format == 'JPEG':
     print('JPEG image')
else:
     print('Invalid image type')
Run Code Online (Sandbox Code Playgroud)

  • 显然,“验证” atm仅适用于PNG。https://github.com/python-pillow/Pillow/issues/3012#issuecomment-368219545 (2认同)