【问题标题】:how to pass image from memory to flask variable如何将图像从内存传递到烧瓶变量
【发布时间】:2021-07-07 15:10:41
【问题描述】:

我想生成一个图并保存到内存中,然后将它作为变量传递给烧瓶,但我被卡住了。我已经编写了这段代码,它似乎可以在 google colab 中工作,当调用该函数时,它会生成绘图。但是我现在想将变量缓冲区传递给烧瓶渲染模板,但我完全卡住了

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=.....)

html 部分应该是...

<body>
    <img id="picture" src="{{ buffer }}">
</body>

【问题讨论】:

  • 也许this 文章可以帮到你。还有这个gist

标签: python flask io


【解决方案1】:

我已经弄清楚了以下内容,它似乎在本教程的基础上起作用

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'))

在html页面上


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

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2017-10-20
    • 2017-11-19
    相关资源
    最近更新 更多