以下代码当然会创建一个名为test的PNG并将其保存在服务器上:
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig = Figure(figsize=[4,4])
ax = fig.add_axes([.1,.1,.8,.8])
ax.scatter([1,2], [3,4])
canvas = FigureCanvasAgg(fig)
canvas.print_figure("test.png")
然后要在浏览器中查看图像,我们必须转到example.com/test.png。这意味着我们必须首先使用Python代码调用页面来创建test.png文件,然后转到PNG文件。有没有办法从创建图像的Python页面绘制PNG和输出?谢谢!
答案 0 :(得分:21)
首先,您需要一个页面来从生成图像的Web服务器控制器加载URL:
<img src="/matplot/makegraph?arg1=foo" />
然后,将matplotlib代码嵌入makegraph
控制器中。您只需要在内存缓冲区中捕获画布呈现的PNG,然后创建HTTP响应并将字节写回浏览器:
import cStringIO
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig = Figure(figsize=[4,4])
ax = fig.add_axes([.1,.1,.8,.8])
ax.scatter([1,2], [3,4])
canvas = FigureCanvasAgg(fig)
# write image data to a string buffer and get the PNG image bytes
buf = cStringIO.StringIO()
canvas.print_png(buf)
data = buf.getvalue()
# pseudo-code for generating the http response from your
# webserver, and writing the bytes back to the browser.
# replace this with corresponding code for your web framework
headers = {
'Content-Type': 'image/png',
'Content-Length': len(data)
}
response.write(200, 'OK', headers, data)
注意:如果经常使用相同的参数生成缓存,则可能需要为这些添加缓存,例如:从args构造一个键并将图像数据写入memcache,然后在重新生成图形之前检查memcache。
答案 1 :(得分:2)
只需为python3更新
StringIO和cStringIO模块不见了。而是导入io 模块并使用io.StringIO https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio
所以现在将是这样:
pthread_key_create()