how to save a pylab figure into in-memory file which can be read into PIL image?

nye17 picture nye17 · Dec 22, 2011 · Viewed 33.2k times · Source

new to PIL, but want to get a quick solution out of it. The following is my first shot which never works:

import cStringIO
import pylab
from PIL import Image
pylab.figure()
pylab.plot([1,2])
pylab.title("test")
buffer = cStringIO.StringIO()
pylab.savefig(buffer, format='png')
im = Image.open(buffer.read())
buffer.close()

the error says,

Traceback (most recent call last):
  File "try.py", line 10, in <module>
    im = Image.open(buffer.read())
  File "/awesomepath/python2.7/site-packages/PIL/Image.py", line 1952, in open
    fp = __builtin__.open(fp, "rb")

any ideas? I don't want the solution to involve extra packages, thanks.

Answer

unutbu picture unutbu · Dec 22, 2011

Remember to call buf.seek(0) so Image.open(buf) starts reading from the beginning of the buf:

import io
from PIL import Image
import matplotlib.pyplot as plt

plt.figure()
plt.plot([1, 2])
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
im.show()
buf.close()