以字符串形式返回 Matplotlib 图像
我在 django 应用程序中使用 matplotlib,想直接返回渲染的图像。 到目前为止,我可以转到 plt.savefig(...),然后返回图像的位置。
我想做的是:
return HttpResponse(plt.renderfig(...), mimetype="image/png")
有什么想法吗?
I am using matplotlib in a django app and would like to directly return the rendered image.
So far I can go plt.savefig(...)
, then return the location of the image.
What I want to do is:
return HttpResponse(plt.renderfig(...), mimetype="image/png")
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Django 的 HttpResponse 对象支持类似文件的 API,您可以将文件对象传递给 savefig。
因此,您可以直接在
HttpResponse
中返回图像。Django's
HttpResponse
object supports file-like API and you can pass a file-object to savefig.Hence, you can return the image directly in the
HttpResponse
.cStringIO 怎么样?
what about cStringIO?
Matplotlib Cookbook 中有一个食谱可以做到这一点。 从本质上讲,它看起来像:
将其放入视图文件中,将 URL 指向它,然后就可以开始运行了。
编辑:如上所述,这是食谱中食谱的简化版本。 但是,至少在我所做的初始测试中,调用
print_png
和savefig
之间似乎存在差异。 调用fig.savefig(response, format='png')
得到的图像更大且具有白色背景,而原始的canvas.print_png(response)
给出带有灰色背景的稍小图像。 因此,我将上面的最后几行替换为:不过,您仍然需要实例化画布。
There is a recipe in the Matplotlib Cookbook that does exactly this. At its core, it looks like:
Put that in your views file, point your URL to it, and you're off and running.
Edit: As noted, this is a simplified version of a recipe in the cookbook. However, it looks like there is a difference between calling
print_png
andsavefig
, at least in the initial test that I did. Callingfig.savefig(response, format='png')
gave an image with that was larger and had a white background, while the originalcanvas.print_png(response)
gave a slightly smaller image with a grey background. So, I would replace the last few lines above with:You still need to have the canvas instantiated, though.
使用 ducktyping 并传递您自己的对象,以文件对象的形式伪装,
您可以在实际代码中使用 myfile = StringIO.StringIO() 代替,并在响应中返回数据,例如
Employ ducktyping and pass a object of your own, in disguise of file object
you can use myfile = StringIO.StringIO() instead in real code and return data in reponse e.g.