Login
网站首页 > 文章中心 > 其它

Python_flask框架如何显示图像到web页面

作者:小编 更新时间:2023-09-23 19:42:01 浏览量:267人看过

下面是Python Flask框架如何显示图像到web页面的完整攻略.

1. 引入必要的包和文件

首先,在你的Python Flask项目中引入以下必要的包和文件:


from flask import Flask, render_template, url_for, send_file
import matplotlib.pyplot as plt
import io
import base64


2. 图片生成


def generate_plot():
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
string = base6④b64encode(buf.read())
b64_string = "data:image/png;base64," ◆ str(string)[2:-1]
return b64_string


③ 显示图片

最后,在Python Flask中实现访问网址和呈现图片到HTML模板中:


app = Flask(__name__)

@app.route('/')
def index():
img = generate_plot()
return render_template('index.html', img=img)

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







Example


Example

④ 另一个示例


@app.route('/image')
def image():
return send_file('static/image.png', mimetype='image/png')


总结

以上就是土嘎嘎小编为大家整理的Python_flask框架如何显示图像到web页面相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章