PIL 处理 PNG 时的问题

2 投票
1 回答
1388 浏览
提问于 2025-04-15 11:52
from PIL import ImageFile as PILImageFile

p = PILImageFile.Parser()

#Parser the data
for chunk in content.chunks():
    p.feed(chunk)    
try:
    image = p.close()
except IOError:                        
    return None
#Here the model is RGBA
if image.mode != "RGB":
    image = image.convert("RGB")

它总是在这里卡住:

image = image.convert("RGB")

File "C:\Python25\Lib\site-packages\PIL\Image.py" in convert
  653.         self.load()
File "C:\Python25\Lib\site-packages\PIL\ImageFile.py" in load
  189.                     s = read(self.decodermaxblock)
File "C:\Python25\Lib\site-packages\PIL\PngImagePlugin.py" in load_read
  365.         return self.fp.read(bytes)
File "C:\Python25\Lib\site-packages\PIL\ImageFile.py" in read
  300.             data = self.data[pos:pos+bytes]

Exception Type: TypeError at 
Exception Value: 'NoneType' object is unsubscriptable

1 个回答

0

这个问题是因为PIL库中的close代码写错了,算是一个bug。

编辑文件(你电脑上的路径可能不一样):

sudo vi /usr/lib64/python2.6/site-packages/PIL/ImageFile.py

在第283行修改:

def close(self):
    self.data = self.offset = None

改成:

def close(self):
    #self.data = self.offset = None
    self.offset = None

就这样,注释掉出错的代码,添加正确的那一行,然后保存文件。完成了,现在运行之前出错的程序,它应该能正常工作了。

撰写回答