0

I want to generate a plot and save to memory and then pass it flask as a variable but I am stuck. I have written this code and it seems to work in google colab, when the function is called it generates the plot. However I want now to pass the variable buffer to flask render template but I am totally stuck

import io

def image_plot():
             plt.figure()
             my_ax = sns.violinplot(x=df_tweet["compound"])
             plt.title('this is the twitter sentiment analysis for')
             buffer = io.BytesIO()
             my_ax.figure.savefig(buffer, format="png")
             buffer.seek(0)
             return buffer


return render_template("index.html", buffer=.....)

and the html part should be...

<body>
    <img id="picture" src="{{ buffer }}">
</body>
1
  • Maybe this article can help you with it. And this gist Commented Jul 7, 2021 at 16:34

1 Answer 1

0

I have figured out the following and it seems to work basing it this tutorial

https://buraksenol.medium.com/pass-images-to-html-without-saving-them-as-files-using-python-flask-b055f29908a

import io
import base64



plt.figure()
my_ax = sns.violinplot(x=df_tweet["compound"])
plt.title('this is saved to memory')
buffer = io.BytesIO()
my_ax.figure.savefig(buffer, format="png")
buffer.seek(0)
image_memory = base64.b64encode(buffer.getvalue())

return render_template("index.html", img_data=image_memory.decode('utf-8'))

on the html page


<img id="picture" src="data:image/png;base64,{{ img_data }}">

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.