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
> error:
> TypeError: Could not convert object to file pointer

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

libpng does not require a file pointer. It can write to streams (or
StringIO objects) too. Cairo uses libpng to write to streams, and
PyCairo uses cairo (and libpng) to write to file-like objects (like
StringIO), so it is possible. But I don't know the details, the
technique is buried somewhere in the cairo and libpng C code.


Send instant messages to your online friends