以字符串形式返回 Matplotlib 图像

发布于 2024-07-26 20:05:03 字数 211 浏览 2 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

奶茶白久 2024-08-02 20:05:03

Django 的 HttpResponse 对象支持类似文件的 API,您可以将文件对象传递给 savefig。

response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response

因此,您可以直接在 HttpResponse 中返回图像。

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

Hence, you can return the image directly in the HttpResponse.

两相知 2024-08-02 20:05:03

cStringIO 怎么样?

import pylab
import cStringIO
pylab.plot([3,7,2,1])
output = cStringIO.StringIO()
pylab.savefig('test.png', dpi=75)
pylab.savefig(output, dpi=75)
print output.getvalue() == open('test.png', 'rb').read() # True

what about cStringIO?

import pylab
import cStringIO
pylab.plot([3,7,2,1])
output = cStringIO.StringIO()
pylab.savefig('test.png', dpi=75)
pylab.savefig(output, dpi=75)
print output.getvalue() == open('test.png', 'rb').read() # True
童话里做英雄 2024-08-02 20:05:03

Matplotlib Cookbook 中有一个食谱可以做到这一点。 从本质上讲,它看起来像:

def simple(request):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure

    fig=Figure()
    ax=fig.add_subplot(111)
    ax.plot(range(10), range(10), '-')
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

将其放入视图文件中,将 URL 指向它,然后就可以开始运行了。

编辑:如上所述,这是食谱中食谱的简化版本。 但是,至少在我所做的初始测试中,调用 print_pngsavefig 之间似乎存在差异。 调用 fig.savefig(response, format='png') 得到的图像更大且具有白色背景,而原始的 canvas.print_png(response) 给出带有灰色背景的稍小图像。 因此,我将上面的最后几行替换为:

    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    fig.savefig(response, format='png')
    return response

不过,您仍然需要实例化画布。

There is a recipe in the Matplotlib Cookbook that does exactly this. At its core, it looks like:

def simple(request):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure

    fig=Figure()
    ax=fig.add_subplot(111)
    ax.plot(range(10), range(10), '-')
    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

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 and savefig, at least in the initial test that I did. Calling fig.savefig(response, format='png') gave an image with that was larger and had a white background, while the original canvas.print_png(response) gave a slightly smaller image with a grey background. So, I would replace the last few lines above with:

    canvas=FigureCanvas(fig)
    response=django.http.HttpResponse(content_type='image/png')
    fig.savefig(response, format='png')
    return response

You still need to have the canvas instantiated, though.

音盲 2024-08-02 20:05:03

使用 ducktyping 并传递您自己的对象,以文件对象的形式伪装,

class MyFile(object):
    def __init__(self):
        self._data = ""
    def write(self, data):
        self._data += data

myfile = MyFile()
fig.savefig(myfile)
print myfile._data

您可以在实际代码中使用 myfile = StringIO.StringIO() 代替,并在响应中返回数据,例如

output = StringIO.StringIO()
fig.savefig(output)
contents = output.getvalue()
return HttpResponse(contents , mimetype="image/png")

Employ ducktyping and pass a object of your own, in disguise of file object

class MyFile(object):
    def __init__(self):
        self._data = ""
    def write(self, data):
        self._data += data

myfile = MyFile()
fig.savefig(myfile)
print myfile._data

you can use myfile = StringIO.StringIO() instead in real code and return data in reponse e.g.

output = StringIO.StringIO()
fig.savefig(output)
contents = output.getvalue()
return HttpResponse(contents , mimetype="image/png")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文