2017-04-05 63 views
1

下面的代碼片斷產生matplotlib情節,並返回一個PNG:繪製從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中嵌入此。 然而,試圖使用jquery來更新圖像時:

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

顯示圖像作爲原始數據 enter image description here

回答

0

事實證明,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