我正在尝试为我的Web应用程序实现图像压缩。虽然压缩对于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上运行两个版本的代码会产生propper结果(图像很好地压缩,质量损失很小)
Sytem规格:
非常感谢任何帮助。
答案 0 :(得分:1)
不确定这是否有帮助,但是我遇到了类似的问题。对我唯一有效的方法是,在安装所需库的 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"