Saving a figure to StringIO or similar

As far as I know (and could very well be wrong)
libpng requires a FILE*, which StringIO and cStringIO do not provide.

I think this is exactly the reason why printing to stdout fails.

Well, if anybody has any other idea I'd be very grateful.

Sascha

···

--
5 GB Mailbox, 50 FreeSMS GMX ProMail - Mehr als E-Mail mit dem Profi-Postfach
+++ GMX - die erste Adresse f�r Mail, Message, More +++

I posted this to the list a few days ago:

Using the agg backend you can obtain an RGBA buffer or RGB string which
can then be loaded as a PIL Image for processing. I've adapted a the
examples/agg_oo.py to demonstrate.

···

On Wed, 2005-08-31 at 08:15 +0200, Sascha GL wrote:

> As far as I know (and could very well be wrong)
> libpng requires a FILE*, which StringIO and cStringIO do not provide.

I think this is exactly the reason why printing to stdout fails.

Well, if anybody has any other idea I'd be very grateful.

----
from matplotlib.backends.backend_agg \
    import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import Image

fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1,2,3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts')
canvas.draw()
size = canvas.get_width_height()
usebuffer = True
if usebuffer:
    # Load the agg buffer directly as the source of the PIL image
    # - could be less stable as agg and PIL share memory.
    buf = canvas.buffer_rgba()
    im = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
else:
    # Save the agg buffer to a string and load this into the PIL image.
    buf = canvas.tostring_rgb()
    im = Image.fromstring('RGB', size, buf, 'raw', 'RGB', 0, 1)

im.show()
----

If you are using a recent CVS version of mpl you will need to change
buffer_rgba() to buffer_rgba(0,0).

Nick