4

当尝试在 PIL python 库中执行以下操作时:

Image.open('Apple.gif').save('Apple.pgm')

代码失败:

  Traceback (most recent call last):
  File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_comm.py", line 765, in doIt
    result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
  File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_vars.py", line 376, in evaluateExpression
    result = eval(compiled, updated_globals, frame.f_locals)
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/usr/lib/python2.7/dist-packages/PIL/PpmImagePlugin.py", line 114, in _save
    raise IOError, "cannot write mode %s as PPM" % im.mode
IOError: cannot write mode P as PPM

该代码在转换为 BMP 时工作正常,但 JPG 也失败。奇怪的是,不同的文件(JPG 到 PGM)可以正常工作。

其他格式转换。那是:

Image.open('Apple.gif').save('Apple.bmp')

作品。

知道为什么吗?

4

1 回答 1

13

您需要将图像转换为RGB模式才能使其正常工作。

im = Image.open('Apple.gif')
im = im.convert('RGB')
im.save('Apple.pgm')
于 2012-10-06T10:46:27.083 回答