如何使用CherryPy返回HTTP响应中的图像 [英] How to return an image in an HTTP response with CherryPy
问题描述
我有生成Cairo ImageSurface
的代码,我这样公开它:
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).
我测试过 surface.write_to_png('test.png')
有效,但我不确定将数据转储到哪里以返回它。我猜一些像文件一样的对象?根据 pycairo文档, get_data()
返回一个缓冲区。我现在也尝试过:
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.
推荐答案
添加这些导入:
from cherrypy.lib import file_generator
import StringIO
然后像这样:
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"'
此外,它是否更好?在内存中创建并保存
这个图像(比如我正在尝试
)或者将它作为temp
文件写入磁盘并从那里提供服务?我只需
需要一次图像,然后它可以被
丢弃。
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.
这篇关于如何使用CherryPy返回HTTP响应中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!