最近使用PIL来做简单的网站图片处理,但是总是出现一些问题,还好Stackoverflow上牛人太多了,搜搜也就有答案了。
web上经常要将图片转成渐进显示的格式,一边在传输图片的同时就可以在web进行比较模糊的展示。下面就是用PIL来做jpg转换的代码:
import Image img = Image.open("in.jpg") img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)报错:
Suspension not allowed here Traceback (most recent call last): File "test.py", line 3, in <module> img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True) File "/Library/Python/2.6/site-packages/PIL/Image.py", line 1439, in save save_handler(self, fp, filename) File "/Library/Python/2.6/site-packages/PIL/JpegImagePlugin.py", line 471, in _save ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)]) File "/Library/Python/2.6/site-packages/PIL/ImageFile.py", line 501, in _save raise IOError("encoder error %d when writing image file" % s) IOError: encoder error -2 when writing image file答案:
这个其实可以转换小图片,但大图片就会出错。解决方法就是增加bufferr。
import PIL from exceptions import IOError img = PIL.Image.open("c:\\users\\adam\\pictures\\in.jpg") destination = "c:\\users\\adam\\pictures\\test.jpeg" try: img.save(destination, "JPEG", quality=80, optimize=True, progressive=True) except IOError: PIL.ImageFile.MAXBLOCK = img.size[0] * img.size[1] img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)简而言之就是要增加PIL.ImageFile.MAXBLOCK的值。
可参见:http://stackoverflow.com/questions/6788398/how-to-save-progressive-jpeg-using-python-pil-1-1-7?answertab=votes#tab-top