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) canvas.draw() imageSize = canvas.get_width_height() imageRgb = canvas.tostring_rgb() pilImage = PIL.Image.fromstring("RGB", imageSize, imageRgb) buffer = StringIO.StringIO() pilImage.save(buffer, "PNG") return buffer.getvalue() def getSvgFromFigure(figure, imageSize): canvas = FigureCanvasSVG(figure) canvas.draw() svgwriter = StringIO.StringIO() renderer = RendererSVG(imageSize[0], imageSize[1], svgwriter) figure.draw(renderer) renderer.finish() 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: Nelson Minar <[EMAIL PROTECTED]> 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 pointerlibpng seems to require an actual file pointer. This was discussed in http://thread.gmane.org/gmane.comp.python.matplotlib.general/3118/ |
------------------------------------------------------------------------- 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