JS发送图片到PYTHON保存与显示
本文介绍如何将网页上canvas中的图片发送到python服务端显示。服务器端使用python flask实现,而客户端使用js jquery ajax实现。
实现JS发送图片
const sendCanvasAsBlob = (canvas) => {
if (canvas.toBlob) {
canvas.toBlob(
function(blob) {
formData = new FormData();
formData.append('image', blob);
$.ajax({
type: "POST",
url: "http://server_address:server_port/videoFrame",
data: formData,
processData: false,
contentType: false
});
},
'image/png'
);
}
}
实现PYTHON接收图片然后保存或者显示
# import the necessary packages
from flask import Flask, request, redirect
from werkzeug import FileStorage
import os
import cv2
import numpy as np
# create an instance of the Flask class
app = Flask(__name__)
# set the update folder and the allowed image extentions
UPLOAD_FOLDER = '/tmp/'
# define the path to where output image will be stored
OUTPUT_PATH = os.path.join(UPLOAD_FOLDER,'testpic.jpg')
@app.route('/videoFrame', methods=['POST'])
def requests(req=None):
file = request.files['image']
if file:
# save the image to storage
# FileStorage(stream=file).save(OUTPUT_PATH)
# read image file string data
filestr = file.read()
# convert string data to numpy array
npimg = np.fromstring(filestr, np.uint8)
# convert numpy array to image
img = cv2.imdecode(npimg, cv2.IMREAD_COLOR)
# show the image
cv2.imshow("mememe", img)
cv2.waitKey()
return "videoFrame"