Returning Matplotlib image as string

前端 未结 4 1977
天命终不由人
天命终不由人 2020-12-31 12:14

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 im

4条回答
  •  没有蜡笔的小新
    2020-12-31 12:28

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

提交回复
热议问题