下面是Python Flask框架如何显示图像到web页面的完整攻略.
首先,在你的Python Flask项目中引入以下必要的包和文件:
from flask import Flask, render_template, url_for, send_file
import matplotlib.pyplot as plt
import io
import base64
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页面相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!