How to return an image in an HTTP response with CherryPy
- by colinmarc
I have code which generates a Cairo ImageSurface, and I expose it like so:
def preview(...):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
...
cherrypy.response.headers['Content-Type'] = "image/png"
return surface.get_data()
preview.exposed = True
This doesn't work (browsers report that the image has errors).
I've tested that surface.write_to_png('test.png') works, but I'm not sure what to dump the data into to return it. I'm guessing some file-like object? According to the pycairo documentation, get_data() returns a buffer. I've also now tried:
tempf = os.tmpfile()
surface.write_to_png(tempf)
return tempf
Also, is it better to create and hold this image in memory (like I'm trying to do) or write it to disk as a temp file and serve it from there? I only need the image once, then it can be discarded.