How to return an image in an HTTP response with CherryPy

时光总嘲笑我的痴心妄想 提交于 2019-12-03 14:05:36

Add these imports:

from cherrypy.lib import file_generator
import StringIO

and then go like this:

def index(self):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    cherrypy.response.headers['Content-Type'] = "image/png"

    buffer = StringIO.StringIO()
    surface.write_to_png(buffer)
    buffer.seek(0)

    return file_generator(buffer)

Additionaly, if you're serving standalone file (i.e. it's not a part of a web page) and you don't want it to be rendered into browser but rather treated as a file to save on a disk then you need one more header:

cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="file.png"'

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.

If the only thing you want to do is to serve this file to a browser there is no reason to create it on a disk on the server. Quite the contrary - remember that accessing hard disk brings performance penalty.

Vitold S.

You're failing because of not understand the working of surface.get_data(). You are trying to return mime-type image/png but surface.get_data() returns plain bitmap image (is not a Windows Bitmap file .BMP with header) which is plain image dump from "virtual screen" (surface)

Like this:

0000010000
0000101000
0001000100
0010000010
0001000100
0000101000
0000010000

Have you tried return str(surface.get_data())?

Try this for 'file in memory' approach

return StringIO.StringIO(surface.get_data())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!