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?
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:
File
"/usr/lib/python2.3/site-packages/matplotlib/backends/backend_agg.py",
line 453, in print_figure
self.renderer._renderer.write_png(filename)
TypeError: Could not convert object to file pointer
The same use of StringIO does work with GD; is this a bug in the Agg
backend? Please see attached test code.
BTW, while I'm here, I noticed a discusison on matplotlib-devel about
how to specify the image format when rendering it to the backend:
http://www.mail-archive.com/matplotlib-devel@lists.sourceforge.net/msg00150.html
I'm in favour of an explicit format argument as well, for exactly the
webapp use case. I'd like to easily be able to get the bytes for either
the PNG or SVG of an image.
#!/usr/bin/python
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
# from matplotlib.backends.backend_gd import FigureCanvasGD as FigureCanvas
import sys
figure = Figure()
ax = figure.add_subplot(111)
ax.plot([1, 5, 3])
canvas = FigureCanvas(figure)
# This works to save image to a file as a PNG
canvas.print_figure("foo.png")
# This works to send image as a PNG to stdout
# canvas.print_figure(sys.stdout)
# Works with GD, but with Agg this doesn't work, error is
# File "/usr/lib/python2.3/site-packages/matplotlib/backends/backend_agg.py",
line 453, in print_figure
# self.renderer._renderer.write_png(filename)
# TypeError: Could not convert object to file pointer
import StringIO
buffer = StringIO.StringIO()
canvas.print_figure(buffer)
print len(buffer.getvalue())
-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users