[英]How to send an image from flask server to javascript display on frontend?
[英]How to send an image directly from flask server to html?
我是不熟悉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發送。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.