Flask给前端返回图片数据流

from flask import Flask
import matplotlib.pyplot as plt
import numpy as np
import io
import sys

app = Flask(__name__)

print(sys.argv)
if len(sys.argv) >= 2:
    file_path = sys.argv[1]
else:
    file_path = ""


print(file_path)


# 定义路由
@app.route("/")  # url访问路径在这里改   "/home/" 意味着 需要访问 127.0.0.1:8000/home/
def index():
    image = np.load(file_path)
    fig = plt.figure()
    plt.imshow(image)
    canvas = fig.canvas

    buffer = io.BytesIO()
    canvas.print_png(buffer)
    data = buffer.getvalue()
    buffer.close()

    # 向前端返回图像
    res = app.make_response(data)
    res.headers["Content-Type"] = "image/png"
    return res


if __name__ == "__main__":

    app.run(port=8000)

你可能感兴趣的:(Flask给前端返回图片数据流)