【问题标题】:Plotting png plot from matplotlib in flask displays raw data在烧瓶中从 matplotlib 绘制 png 图显示原始数据
【发布时间】:2017-04-05 06:53:12
【问题描述】:

以下sn-p代码生成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+'" />')
      })

将图像显示为原始数据

【问题讨论】:

    标签: python matplotlib flask


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 2018-02-18
      • 2012-10-06
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多