如何将图像直接从Flask服务器发送到html?

时间:2019-07-09 07:02:00

标签: javascript python flask

我是不熟悉烧瓶的人,正在尝试制作一个应用程序,以便图像由网络摄像头的html和js拍摄,然后将其与ajax请求一起发送到服务器。我有这部分。然后,对图像进行一些处理,并且必须将其发送回前端。我知道如何在烧瓶中正常发送数据,如

@app.route('/')
def function():
    return render_template("index.html", data = data)

但是在python中,图像是numpy数组的形式,而js无法读取numpy数组并将其转换为图像(至少我不知道这样做的任何方式)。那么这是怎么做的呢?

1 个答案:

答案 0 :(得分:1)

这显示了如何将numpy数组转换为PIL.Image,然后将其与io.BytesIO一起使用以在内存中创建文件PNG。

然后您可以使用send_file()将PNG发送到客户端。

from flask import Flask, send_file
from PIL import Image
import numpy as np
import io

app = Flask(__name__)

raw_data = [
    [[255,255,255],[0,0,0],[255,255,255]],
    [[0,0,1],[255,255,255],[0,0,0]],
    [[255,255,255],[0,0,0],[255,255,255]],
]

@app.route('/image.png')
def image():
    # my numpy array 
    arr = np.array(raw_data)

    # convert numpy array to PIL Image
    img = Image.fromarray(arr.astype('uint8'))

    # create file-object in memory
    file_object = io.BytesIO()

    # write PNG in file-object
    img.save(file_object, 'PNG')

    # move to beginning of file so `send_file()` it will read from start    
    file_object.seek(0)

    return send_file(file_object, mimetype='image/PNG')


app.run()

使用与GIF或JPG相同的发送方式。