2

The following snippet of code generates a matplotlib plot and returns a 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')

Embedding this in html:

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

works as expected. However, when trying to update the image using jquery:

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

displays the image as raw data enter image description here

1 Answer 1

1

It turns out that base64 encoding was necessary:

    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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.