尝试使用PIL保存图像时出现IndexError [英] IndexError when trying to save an image with PIL
问题描述
我正在尝试将用户提交的PNG图像转换为JPEG,但是当我尝试保存图像时,我得到了
I am trying to convert the PNG images that the user submits to JPEG, but when I try to save the image, I get
<type 'exceptions.IndexError'>: string index out of range
我正在使用CGI在Apache中运行python脚本.当我在控制台中运行脚本时,它可以正常运行.
I am running the python script in Apache using CGI. When I run the script in console, it works ok.
这是代码.
if imghdr.what(filePath) == 'png':
p = Image.open(filePath)
p.save('../files/outfile.jpg', "JPEG")
filePath = "../files/outfile.jpg"
该错误发生在p.save()行上.我以为这是一个权限问题,但是我什至给了files/目录777权限,但仍然无法使用.
The error occurs on the p.save() row. I thought that it was a permission problem, but I even gave 777 permissions on the files/ directory and it still won't work.
编辑 这就是save()调用之后的结果.
EDIT This is what comes after the save() call.
/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',)
推荐答案
我将自己回答,因为Hugo没有发布答案.
I'm gonna answer this myself since Hugo didn't post an answer.
有一个名为 LOAD_TRUNCATED_IMAGES 的标志,默认情况下设置为 False .
There is a flag called LOAD_TRUNCATED_IMAGES that is set to False by default.
您必须转到/usr/lib/python2.7/dist-packages/PIL/ImageFile.py ,并将其设置为 True .
You have to go to /usr/lib/python2.7/dist-packages/PIL/ImageFile.py and set it to True.
这篇关于尝试使用PIL保存图像时出现IndexError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!