首页 > 解决方案 > 如何将图像直接从烧瓶服务器发送到 html?

问题描述

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

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

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

标签: javascriptpythonflask

解决方案


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


推荐阅读