【背景】使用PIL进行图片预处理,检查不完整的图片。可以使用Load()方法和verify方法。
【报错】根据load和verify的顺序不同,可能的报错有以下几种:
一、先使用load再使用verify:
AttributeError: 'NoneType' object has no attribute 'close'
二、先使用verify再load:
AttributeError: 'JpegImageFile' object has no attribute 'load_seek'
AttributeError: 'NoneType' object has no attribute 'seek'
【原因】使用verify(或load)检查图片之后,如果需要再进行load(verify)检查,需要重新再open图片
【解决】举例:open -> verify -> close -> open -> load 或者 open -> verify -> open -> load
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> from PIL import Image
>>> f = Image.open('truncated_5482.JPG')
>>> f.load()
<PixelAccess object at 0x000001FC6D500DB0># 一、先load后verify,没有重新open,verify报错
>>> f.verify()
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFile.py", line 134, in verifyself.fp.close()
AttributeError: 'NoneType' object has no attribute 'close'# 二、先verify后load,没没有重新open,load报错
>>> f = Image.open('truncated_5482.JPG')
>>> f.verify()
>>> f.load()
Traceback (most recent call last):File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFile.py", line 163, in loadseek = self.load_seek
AttributeError: 'JpegImageFile' object has no attribute 'load_seek'During handling of the above exception, another exception occurred:Traceback (most recent call last):File "<stdin>", line 1, in <module>File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFile.py", line 166, in loadseek = self.fp.seek
AttributeError: 'NoneType' object has no attribute 'seek'# 对于二,正确的做法(对于一,同理):
>>> f = Image.open('truncated_5482.JPG')
>>> f.verify()
>>> f = Image.open('truncated_5482.JPG')# 可选
>>> f.close()# 不再报错
>>> f.load()
<PixelAccess object at 0x000001FC6D5006D0>