title: How to return an image in an HTTP response with CherryPy
body: <p>I have code which generates a Cairo <code>ImageSurface</code>, and I expose it like so:</p>
  
  <pre><code>def preview(...):
      surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
      ...
      cherrypy.response.headers['Content-Type'] = "image/png"
      return surface.get_data()
  preview.exposed = True
  </code></pre>
  
  <p>This doesn't work (browsers report that the image has errors).</p>
  
  <p>I've tested that <code>surface.write_to_png('test.png')</code> works, but I'm not sure what to dump the data into to return it. I'm guessing some file-like object? According to <a href="http://cairographics.org/documentation/pycairo/2/reference/surfaces.html#class-imagesurface-surface" rel="noreferrer">the pycairo documentation</a>, <code>get_data()</code> returns a buffer. I've also now tried:</p>
  
  <pre><code>tempf = os.tmpfile()
  surface.write_to_png(tempf)
  return tempf
  </code></pre>
  
  <p>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. </p>