Skip to main content
 首页 » 编程设计

python之从 flask 中的 matplotlib 绘制 png 图显示原始数据

2025年02月15日7zhengyun_ustc

以下代码片段生成一个 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+'" />') 
      }) 

将图像显示为原始数据

请您参考如下方法:

原来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