从烧瓶中的matplotlib绘制png图显示原始数据

时间:2017-04-05 06:53:12

标签: python matplotlib flask

以下代码片段生成一个matplotlib图并返回一个png:

@app.route('/plot/')    
def test_image():
        fig, ax = plt.subplots(1)
        plt.plot(np.arange(100), np.random.normal(0, 1, 100))
        canvas = FigureCanvas(fig)
        img = BytesIO()
        fig.savefig(img)
        img.seek(0)
        return send_file(img, mimetype='image/png')

将其嵌入html:

<img src="{{ url_for('test_image') }}" alt="Image Placeholder" height="300">

按预期工作。 但是,尝试使用jquery更新图像时:

$.get('/plot', function(image){
          $("#weapImage").html('<img src="data:image/png;base64,'+image+'" />')
      })

将图像显示为原始数据 enter image description here

1 个答案:

答案 0 :(得分:1)

事实证明,base64编码是必要的:

    fig, ax = plt.subplots(1)
    plt.plot(np.arange(100), np.random.normal(0, 1, 100))
    img = BytesIO()
    fig.savefig(img)
    img.seek(0)
    resp = Response(response=base64.b64encode(img.getvalue()),
                    status=200, mimetype="image/png")
    return resp