使用PIL保存图片时出现IndexError

3 投票
1 回答
1644 浏览
提问于 2025-04-18 16:13

我正在尝试把用户提交的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',)

1 个回答

5

我来自己回答这个问题,因为Hugo没有发答案。

有一个叫做 LOAD_TRUNCATED_IMAGES 的标志,默认是 False,也就是不启用。

你需要去 /usr/lib/python2.7/dist-packages/PIL/ImageFile.py 这个文件,把它改成 True

撰写回答