Agg backend writing to StringIO?

Nelson Minar <nelson@...45...> writes:

matplotlib is great, particularly the image quality. I'm using
matplotlib to generate images in a webapp and have run into a problem.
How do I get it to give me the rendered image bytes in a string rather
than writing the image to a file?

FigureCanvasAgg has the undocumented methods buffer_rgba,
tostring_argb, and tostring_rgb, which might help here.

The docs for FigureCanvasAgg.print_figure() says that if the filename
is actually a file object then it will write the bytes to that file
object. This works great if I pass in sys.stdout, but as soon as I try
to use a StringIO() instance to capture the bytes in Python I get an


TypeError: Could not convert object to file pointer

libpng seems to require an actual file pointer. This was discussed in



Thanks for the answers. I was glad to see Steven Chaplin suggest that
it is possible to get libpng to write directly to a stream like
StringIO; seems like a good thing. In the meantime I came up with the
following little helper functions to render a Figure to PNG (via Agg)
or SVG (via SVG).

def getPngFromFigure(figure, imageSize):

canvas = FigureCanvasAgg(figure)


imageSize = canvas.get_width_height()

imageRgb = canvas.tostring_rgb()

pilImage = PIL.Image.fromstring("RGB", imageSize, imageRgb)

buffer = StringIO.StringIO(), "PNG")

return buffer.getvalue()

def getSvgFromFigure(figure, imageSize):

canvas = FigureCanvasSVG(figure)


svgwriter = StringIO.StringIO()

renderer = RendererSVG(imageSize[0], imageSize[1], svgwriter)



return svgwriter.getvalue()

This code works, and while I don’t really understand matplotlib
internals I think I’m mostly doing things right. Two minor problems:

The Agg images are RGB, no alpha channel. Amusingly enough Agg gives
you ARGB but PIL only understands RGBA.

My code is ignoring whatever size the Figure itself thinks it should be.

Jouni K Seppanen wrote: