如何使用Python PIL 1.1.7保存渐进式JPEG?
我在尝试保存时遇到了错误,但如果我去掉了“渐进式”和“优化”这两个选项,就能成功保存。
这是我测试用的 test.py 文件,但它不工作:
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
图片链接:http://static.cafe.nov.ru/in.jpg (4.3 mb)
3 个回答
4
如果你是通过pip安装了PIL,先把它卸载掉,然后安装pillow。pillow这个库是PIL库的升级版,功能更强大。而通过pip安装的PIL版本太旧了。如果你换成pillow,就不需要手动设置PIL.ImageFile.MAXBLOCK这个参数了,系统会自动处理好。
如果你是用git子模块或者直接下载了PIL的源代码到你的项目里,记得去GitHub上下载最新的源代码来用。
41
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(Python图像库)一次只处理图像的一部分。这和“优化”和“渐进式”选项是冲突的。
补充说明: 对于新版本的PIL / Pillow,你需要先 import PIL.Image, PIL.ImageFile
。
27
这里有一个可能有效的小技巧,不过你可能需要把缓冲区做得更大一些:
from PIL import Image, ImageFile
ImageFile.MAXBLOCK = 2**20
img = Image.open("in.jpg")
img.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)