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

2023-12-25

我是 Flask 的新手,我正在尝试制作一个应用程序,这样图像是由 html 和 js 从网络摄像头拍摄的,然后通过 ajax 请求发送到服务器。我得到了这部分。然后对图像进行一些处理,并且必须将其发送回前端。我知道如何在烧瓶中正常发送数据,如

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

但在 python 中,图像采用 numpy 数组的形式,js 无法读取 numpy 数组并将其转换为图像(至少我不知道有什么方法可以做到这一点)。那么有什么方法可以做到这一点呢?


这显示了如何转换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 发送。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将图像直接从flask服务器发送到html? 的相关文章

随机推荐