savefig to StringIO and import into PIL

Hi mpl users,

I am trying to save a figure to a file like object (a StringIO object)
and load this object into PIL (Python Imaging Library). The code for
this is really simple (fig is my figure object):

# This works
fig.savefig('test.png', format='png')
im = Image.open('test.png')

# This fails
imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
im = Image.open(imgdata)

  File "/home/jl/testfile.py", line 551, in contour
    im = Image.open(imgdata)
  File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1916, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file

Does anyone know what I am doing wrong? I would really like to avoid
putting the image on disk before opening it in PIL since I am using
the code in a web application where speed is important.

Best regards,
Jesper

Jesper Larsen wrote:

Hi mpl users,

I am trying to save a figure to a file like object (a StringIO object)
and load this object into PIL (Python Imaging Library). The code for
this is really simple (fig is my figure object):

# This works
fig.savefig('test.png', format='png')
im = Image.open('test.png')

# This fails
imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
im = Image.open(imgdata)

  File "/home/jl/testfile.py", line 551, in contour
    im = Image.open(imgdata)
  File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1916, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file
  

You need to "rewind" the StringIO cursor before opening with PIL:

imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)
im = Image.open(imgdata)

Hope that helps,
Mike

···

--
Michael Droettboom
Science Software Branch
Operations and Engineering Division
Space Telescope Science Institute
Operated by AURA for NASA

Hi Michael,

2008/10/22 Michael Droettboom <mdroe@...86...>:

You need to "rewind" the StringIO cursor before opening with PIL:

imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)
im = Image.open(imgdata)

Thanks. It works fine now.

Best regards,
Jesper