简体   繁体   English

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

[英]How to send an image directly from flask server to html?

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. 我是不熟悉Flask的人,正在尝试制作一个应用程序,使得图像由html和js从网络摄像头获取,然后将其与ajax请求一起发送至服务器。 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)

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). 但是在python中,图像是numpy数组的形式,而js无法读取numpy数组并将其转换为图像(至少我不知道有什么方法可以做到这一点)。 so what is the way this can be done? 那么这是怎么做的呢?

This shows how to convert numpy array to PIL.Image and then use it with io.BytesIO to create file PNG in memory. 这显示了如何将numpy数组转换为PIL.Image ,然后将其与io.BytesIO一起使用以在内存中创建文件PNG。

And then you can use send_file() to send PNG to client. 然后,您可以使用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()

The same way you can send it as GIF or JPG. 可以将其作为GIF或JPG发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM