本文介绍了将Matplotlib图像作为字符串返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在django应用程序中使用matplotlib,并且想直接返回渲染的图像。
到目前为止,我可以去 plt.savefig(...)
,然后返回图像的位置。
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.
我想做的是:
return HttpResponse(plt.renderfig(...), mimetype="image/png")
有什么想法吗?
推荐答案
Django的 HttpResponse
对象支持类似文件的API,您可以将文件对象传递给savefig。
Django's HttpResponse
object supports file-like API and you can pass a file-object to savefig.
response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response
因此,您可以直接在 HttpResponse
中返回图像。
Hence, you can return the image directly in the HttpResponse
.
这篇关于将Matplotlib图像作为字符串返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!