javascript - 如何将图像直接从烧瓶服务器发送到 html?
问题描述
我是烧瓶的新手,正在尝试制作一个应用程序,这样的图像由网络摄像头的 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 发送。
推荐阅读
- c# - Using Contains() on Included entity
- amazon-web-services - EC2 实例详细信息
- php - PHP ForEach 循环中的 Bootstrap 4 模式
- .net - 有没有办法使用 .NET 从 Matlab 中的标准输入读取 FFPLAY?
- mysql - MySQL 每部电影的平均流派数
- sql-server - 如何创建一个通过 DATETIME 列更新的 DATE 列
- javascript - 特定数据的加密与 Bcrypt
- teradata - teradata studio 使用 Fastexport 排序导出
- python - Python 值未正确附加到 3D 数组
- firebase - Restrict Firestore access to authenticated users