将Matplotlib图像作为字符串返回

时间:2009-07-10 10:46:43

标签: python django matplotlib

我在django应用程序中使用matplotlib,并希望直接返回渲染的图像。 到目前为止,我可以去plt.savefig(...),然后返回图像的位置。

我想做的是:

return HttpResponse(plt.renderfig(...), mimetype="image/png")

有什么想法吗?

4 个答案:

答案 0 :(得分:17)

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

中返回图像

答案 1 :(得分:6)

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

答案 2 :(得分:2)

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

将其添加到您的视图文件中,将您的网址指向该文件,然后即可关闭并运行。

编辑:如上所述,这是食谱中食谱的简化版本。但是,看起来调用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

但仍需要实例化画布。

答案 3 :(得分:0)

使用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")