4

When trying to do the following in the PIL python library:

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

the code fails with:

  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

The code works fine with conversion to BMP, but JPG also fails. Strange thing is, a different file(JPG to PGM), works ok.

Other format conversion. That is:

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

works.

Any idea why?

Pedro Romano
  • 10,973
  • 4
  • 46
  • 50
eran
  • 14,496
  • 34
  • 98
  • 144
  • i think this can help here: http://stackoverflow.com/questions/10269099/pil-convert-gif-frames-to-jpg – fecub Oct 06 '12 at 10:38

1 Answers1

13

You need to convert the image to RGB mode to make this work.

im = Image.open('Apple.gif')
im = im.convert('RGB')
im.save('Apple.pgm')
Junuxx
  • 14,011
  • 5
  • 41
  • 71
  • 1
    `PGM` is a 8 bit grayscale PIL ([mode 'L'](http://www.pythonware.com/library/pil/handbook/concepts.htm) format), whereas GIF is a 8 bit colour palette format (mode 'P'), so you need to and intermediate conversion to a common format. – Pedro Romano Oct 06 '12 at 10:50