如何将图像直接从Flask服务器发送到html? [英] How to send an image directly from flask server to html?
问题描述
我是不熟悉烧瓶的人,正在尝试制作一个应用程序,以便图像由网络摄像头的html和js拍摄,然后将其与ajax请求一起发送到服务器.我有这部分.然后,对图像进行一些处理,并且必须将其发送回前端.我知道如何在烧瓶中正常发送数据,如
I am new to flask and am trying to make an app such an image is taken by the html and js from the webcam and then it is sent to the server with ajax request. I got this part. Then some processing is done on the image and it has to be sent back to the frontend. I know how to send data normally in flask, as in
@app.route('/')
def function():
return render_template("index.html", data = data)
但是在python中,图像是numpy数组的形式,而js无法读取numpy数组并将其转换为图像(至少我不知道这样做的任何方式).那么这是怎么做的呢?
But in python images are in form of numpy arrays and js cannot read numpy arrays and convert it to images( atleast I don't know of any way to do that). so what is the way this can be done?
推荐答案
这显示了如何将 numpy
数组转换为 PIL.Image
,然后将其与一起使用io.BytesIO
在内存中创建文件PNG.
This shows how to convert numpy
array to PIL.Image
and then use it with io.BytesIO
to create file PNG in memory.
然后您可以使用 send_file()
将PNG发送到客户端.
And then you can use send_file()
to send PNG to client.
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相同的发送方式.
The same way you can send it as GIF or JPG.
这篇关于如何将图像直接从Flask服务器发送到html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!