使用PIL保存图像时出现IndexError错误

3
我正在尝试将用户提交的PNG图像转换为JPEG格式,但当我尝试保存图像时,出现以下错误:
<type 'exceptions.IndexError'>: string index out of range 

我在Apache上使用CGI运行Python脚本。当我在控制台中运行脚本时,它可以正常工作。
以下是代码。
if imghdr.what(filePath) == 'png':
    p = Image.open(filePath)
    p.save('../files/outfile.jpg', "JPEG")
    filePath = "../files/outfile.jpg"

错误发生在p.save()这一行。我以为这是权限问题,但即使我在files/目录上给予777权限也无法解决。
编辑:这是save()调用之后的内容。
 /usr/lib/python2.7/dist-packages/PIL/Image.py in save(self=<PIL.PngImagePlugin.PngImageFile image mode=RGB size=512x512>, fp='../files/outfile.jpg', format='JPEG', **params={})
   1434 
   1435         # may mutate self!
=> 1436         self.load()
   1437 
   1438         self.encoderinfo = params
self = <PIL.PngImagePlugin.PngImageFile image mode=RGB size=512x512>, self.load = <bound method PngImageFile.load of <PIL.PngImagePlugin.PngImageFile image mode=RGB size=512x512>>
 /usr/lib/python2.7/dist-packages/PIL/ImageFile.py in load(self=<PIL.PngImagePlugin.PngImageFile image mode=RGB size=512x512>)
    204                             break
    205                         else:
=>  206                             raise IndexError(ie)
    207 
    208                     if not s: # truncated jpeg
builtin IndexError = <type 'exceptions.IndexError'>, ie = IndexError('string index out of range',)

请提供更多的堆栈跟踪行。你尝试使用绝对路径了吗? - deets
在问题中添加了跟踪。 - Stefan Manciu
我也尝试使用绝对路径。但是仍然没有改变。 - Stefan Manciu
1
它会引发错误,因为PNG被截断了。您可以尝试编辑PIL的ImageFile.py并将LOAD_TRUNCATED_IMAGES设置为True。或者,为什么PNG被截断了?其他PNG是否也会发生同样的情况?您能在其他图像查看器中打开它们吗?使用Pillow而不是PIL是否会发生相同的情况? - Hugo
我第一次编辑了错误的文件。现在我将LOAD_TRUNCATED_IMAGES设置为True,它可以正常工作了。谢谢。请将其发布为答案。 - Stefan Manciu
1个回答

5

由于 Hugo 没有发布答案,我会自己回答这个问题。

有一个名为 LOAD_TRUNCATED_IMAGES 的标志,其默认值为 False

您需要前往/usr/lib/python2.7/dist-packages/PIL/ImageFile.py并将其设置为True


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接