生成图像并将其显示在Flask上

2024-10-03 23:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Flask框架的新手,我正在尝试在Flask上展示一些在程序中生成的图像,如wordcloud、图形和图表。我试图存储在image列表中生成的图像,然后返回它。然后在HTML文件中使用它来显示每个图像。在这里,我刚刚进入wordcloud生成部分和app.route部分

from wordcloud import WordCloud
import base64
images = []
def analyse(df)
    # genrate a word cloud image
    wordcloud = WordCloud(
        background_color='white',
        max_words=200,
        max_font_size=40,
        scale=3,
        random_state=42
    ).generate(str(df["Review"]))

    figfile3 = BytesIO()
    plt.savefig(figfile3, format='png')
    figfile3.seek(0)  # rewind to beginning of file
    wordcloudimg = base64.b64encode(figfile3.getvalue())
    images.append(wordcloudimg)
    return images

df["Review"]有文本评论

@app.route('/')
def finaldef():
    images = analyse(df)
    return render_template('pages.html', image=images)

if __name__ == "__main__":
    app.run(debug=True)

页面HTML文件的一部分是

{% block head %}
<title>Pages</title>
{% endblock %}

{% block body %}
<h1>Images</h1>
    {% for i in image %}
        <img src="data:image/png;base64,{{ i }}" width="500">
    {% endfor %}
{% endblock %}

输出是图像符号,而不是我生成的wordcloud。 我真的很感激你的帮助。 多谢各位


Tags: 文件图像imageimportappflaskdfdef
1条回答
网友
1楼 · 发布于 2024-10-03 23:18:22

我猜一猜,因为我还不能用单词云库进行测试

base64.b64encode返回类型为bytes的对象

修复方法可能只是对其返回值进行解码,因此得到类型str。修改代码以执行此操作:

    wordcloudimg = base64.b64encode(figfile3.getvalue()).decode('utf-8')

相关问题 更多 >