How to return an image in an HTTP response with CherryPy
        Posted  
        
            by colinmarc
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by colinmarc
        
        
        
        Published on 2010-06-17T18:15:32Z
        Indexed on 
            2010/06/17
            22:33 UTC
        
        
        Read the original article
        Hit count: 420
        
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.
© Stack Overflow or respective owner