Skip to main content
 首页 » 编程设计

保存图像时 Python Pillow 编码器错误 -2

2025年02月15日7sky-heaven

我正在尝试为我的网络应用程序实现图像压缩。虽然对 PNG 图像压缩效果很好(实际压缩可以忽略不计但没有错误),但对 JPG 和 JPEG 图像压缩失败。

运行 Pillow 测试会产生以下输出:

Pillow 4.1.0 TEST SUMMARY 
-------------------------------------------------------------------- 
Python modules loaded from /usr/local/lib/python2.7/dist-packages/PIL 
Binary modules loaded from /usr/local/lib/python2.7/dist-packages/PIL 
-------------------------------------------------------------------- 
--- PIL CORE support ok 
*** TKINTER support not installed 
--- FREETYPE2 support ok 
*** LITTLECMS2 support not installed 
*** WEBP support not installed 
--- JPEG support ok 
*** OPENJPEG (JPEG2000) support not installed 
--- ZLIB (PNG/ZIP) support ok 
*** LIBTIFF support not installed 
-------------------------------------------------------------------- 
Running selftest: 
--- 58 tests passed. 

看起来一切正常,但在运行我的示例代码时出现以下错误:

Wrong JPEG library version: library is 62, caller expects 90 
Traceback (most recent call last): 
  File "test.py", line 10, in <module> 
    im.save("compressed.jpeg", format="JPEG", quality=90, optimize=True) 
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 1675, in save 
    save_handler(self, fp, filename) 
  File "/usr/local/lib/python2.7/dist-packages/PIL/JpegImagePlugin.py", line 708, in _save 
    ImageFile._save(im, fp, [("jpeg", (0, 0)+im.size, 0, rawmode)], bufsize) 
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageFile.py", line 486, in _save 
    raise IOError("encoder error %d when writing image file" % s) 
IOError: encoder error -2 when writing image file 

我已经在线检查了 Jessie libjpeg 包,62 似乎是最新的,此时我不确定我正在尝试做的事情是否可行。虽然这个问题似乎很常见,但我未能找到解决方案。

我尝试运行的代码如下:

from PIL import Image, ImageFile 
import sys 
 
ImageFile.LOAD_TRUNCATED_IMAGES = True 
 
im = Image.open("original.jpg") 
im.save("compressed.jpg", format="JPEG", quality=90, optimize=True) 
print "Done ..." 

如果我尝试将其转换为:

from PIL import Image, ImageFile 
import sys 
 
ImageFile.LOAD_TRUNCATED_IMAGES = True 
 
im = Image.open("original.jpg") 
im.save("compressed.png", format="PNG", quality=90, optimize=True) 
print "Done ..." 

它不会产生错误,只是使图像变黑。

在 Windows10 上运行两个版本的代码会产生正确的结果(图像压缩得很好,质量损失很小)

系统规范:

  • python 2.7.9
  • 枕头 4.1.0
  • libjpeg62-turbo-dev
  • Debian 杰西

如有任何帮助,我们将不胜感激。

请您参考如下方法:

不确定这是否有帮助,但我遇到了类似的问题。唯一对我有用的是在安装所需库的 dev 版本后强制 pip 从源构建枕头(我的代码是编辑 jpg 并使用自定义字体添加标签)。这是在使用 Python 3.7.3 运行 Ubuntu Linux 的基于 ARM 的嵌入式设备上

apt-get install -y libjpeg-dev libfreetype6-dev 
pip3 install pillow --global-option="build_ext" --global-option="--enable-jpeg" --global-option="--enable-freetype"