from PIL import Image
from flask import Flask
import PIL
import matplotlib.pyplot as plt
import numpy as np
import io
app = Flask(__name__)
# 定义路由
@app.route("/")
def index():
# 数据准备
x = np.arange(10)
y = x
# plt.plot(x,y)
# canvas = plt.get_current_fig_manager().canvas
# canvas.draw()
fig = plt.figure()
plt.plot(x, y)
canvas = fig.canvas
# 上面这段代码和上面注释掉的代码效果一样
# 方法1
buffer = io.BytesIO()
canvas.print_png(buffer)
data = buffer.getvalue()
buffer.close()
# 方法2
# buf, size = canvas.print_to_buffer()
# image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
# buffer = io.BytesIO()
# image.save(buffer, 'PNG')
# data = buffer.getvalue()
# buffer.close()
# 向前端返回图像
res = app.make_response(data)
res.headers["Content-Type"] = "image/png"
return res
if __name__ == "__main__":
app.run()
python 生成的图像直接作为图像流返还给前端(flask方法实现)
最新推荐文章于 2024-04-08 16:51:33 发布