尝试使用PIL保存图像时的IndexError

时间:2014-08-06 12:05:38

标签: python python-imaging-library

我正在尝试将用户提交的PNG图像转换为JPEG,但是当我尝试保存图像时,我得到了

<type 'exceptions.IndexError'>: string index out of range 

我正在使用CGI在Apache中运行python脚本。当我在控制台中运行脚本时,它可以正常工作。

这是代码。

if imghdr.what(filePath) == 'png':
    p = Image.open(filePath)
    p.save('../files/outfile.jpg', "JPEG")
    filePath = "../files/outfile.jpg"

p.save()行发生错误。我认为这是一个权限问题,但我甚至在文件/目录上提供了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',)

1 个答案:

答案 0 :(得分:5)

我会自己回答这个问题,因为雨果没有发表答案。

默认情况下,有一个名为 LOAD_TRUNCATED_IMAGES 的标记设置为 False

您必须转到 /usr/lib/python2.7/dist-packages/PIL/ImageFile.py 并将其设置为 True