Python图像库无法将PNG保存为JPG

3 投票
4 回答
3672 浏览
提问于 2025-04-17 06:31

我在Mac OSX上从源代码安装了PIL 1.1.7。
我还通过Macports安装了所需的库。
我使用的是python 2.6。

安装完PIL后,我成功运行了selftest.py(所有测试都通过了)。

但是,当我尝试运行以下代码时,发现我无法将PNG格式转换为JPG格式。不过,我可以将PNG转换为GIF,PNG转换为PPM格式。我也可以读取JPG文件。

import os
import sys 
import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f + ".jpg"
    print outfile
    if infile != outfile:
        try:
            Image.open(infile).save(outfile, 'jpg') #Note: gif or ppm works
        except IOError:
            print "cannot convert", infile
            if os.path.exists(outfile):
               print 'cleaning up...'
               os.remove(outfile)

** 更新了堆栈跟踪。看起来编码器缺失。不过,我确实通过macport安装了libjpeg。

正在清理...

Traceback (most recent call last):
  File "convert_to_jpeg.py", line 15, in <module>
    Image.open(infile).save(outfile, 'jpeg')
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.py", line 471, in _save
    ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/ImageFile.py", line 495, in _save
    e = Image._getencoder(im.mode, e, a, im.encoderconfig)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/Image.py", line 401, in _getencoder
    raise IOError("encoder %s not available" % encoder_name)
IOError: encoder jpeg not available

4 个回答

1

你正在听我的歌。

我在PIL中搞JPEG支持搞了好几个星期,最后找到这个链接:http://proteus-tech.com/blog/cwt/install-pil-in-snow-leopard/

这是唯一有效的解决办法。我在卸载和重新安装的过程中遇到的麻烦细节在这里:http://www.thetoryparty.com/2010/08/31/pil-on-snow-leopard-_jpeg_resync_to_restart-error/

我做的总结:

1) 强制将gcc和gcov的路径设置为4.2(之前为了安装MySQLdb把它们设置成了4.0)

2) 在我的.profile文件中,注释掉了一些ARCHFLAGS的行(这可能是可选步骤?)

3) 在系统中仔细查找,删除所有叫“libjpeg”、“PIL”或“Imaging”的东西——彻底清理一下

4) 按照上面proteus-tech链接的步骤,从下载一个新的libjpeg开始。

祝你好运!你可以做到的!

(附注:如果你在运行selftest.py时遇到错误——特别是“IOError: decoding error when reading image file”——而且无法加载JPEG,那么这个过程解决了那个问题:

http://www.thetoryparty.com/2011/04/07/pil-and-jpeg-decoding-error-the-revenge/ 如果你以后遇到更多麻烦,这可能会对你有帮助。

注意这两个问题都与libjpeg需要用“-arch i386”构建,而不是“-arch x86_64”有关。这就是64位的乐趣所在!)

2

感谢@jterrace推荐使用homebrew。

解决方案:

Install homebrew 
brew install python 
brew install pil
4

使用 jpeg 而不是 jpg 来表示格式。

撰写回答