繁体   English   中英

通过ajax从网络摄像头发送imageObject到Flask Server

[英]Send imageObject from webcam by ajax to Flask Server

我想从网络摄像头获取快照并将其通过ajax发送到Flask服务器

我有upload.html从网络摄像头获取快照并通过ajax发送,但是我对Flask服务器了解不多,这些服务器从Ajax获取数据并将其保存在特定位置(/图像)

这是upload.html。 网络摄像头仅适用于Firefox(不适用于Chrome)。 我尚未测试的其他浏览器

  //-------------------- // GET USER MEDIA CODE //-------------------- navigator.getUserMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); var video; var webcamStream; function startWebcam() { if (navigator.getUserMedia) { navigator.getUserMedia ( // constraints { video: true, audio: false }, // successCallback function(localMediaStream) { video = document.querySelector('video'); video.src = window.URL.createObjectURL(localMediaStream); webcamStream = localMediaStream; }, // errorCallback function(err) { console.log("The following error occured: " + err); } ); } else { console.log("getUserMedia not supported"); } } //--------------------- // TAKE A SNAPSHOT CODE //--------------------- var canvas, ctx; function init() { // Get the canvas and obtain a context for // drawing in it canvas = document.getElementById("myCanvas"); context = canvas.getContext('2d'); } function snapshot() { // Draws current image from the video element into the canvas context.drawImage(video, 0,0, canvas.width, canvas.height); webcamStream.stop(); var dataURL = canvas.toDataURL('image/jpeg', 1.0); document.querySelector('#dl-btn').href = dataURL; $.ajax({ type: "POST", contentType: false, cache: false, processData: false, async: false, url: "/upload", data: { imgBase64: dataURL } }).done(function(o) { console.log('saved'); // If you want the file to be visible in the browser // - please modify the callback in javascript. All you // need is to return the url to the file, you just saved // and than put the image in your browser. }); } 
 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="camera.js"></script> </head> <body onload="init();"> <h1>Take a snapshot of the current video stream</h1> Click on the Start WebCam button. <p> <button onclick="startWebcam();">Start WebCam</button> <button type="submit" id="dl-btn" href="#" download="participant.jpeg" onclick="snapshot();">Take Snapshot</button> </p> <video onclick="snapshot(this);" width=400 height=400 id="video" controls autoplay></video> <p> Screenshots : <p> <canvas id="myCanvas" width="400" height="350"></canvas> </body> </html> 

这是我的服务器代码:app_basic.py

import os
from flask import Flask, render_template, request, send_from_directory
app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    return render_template("upload.html")

 @app.route("/upload", methods=['POST'])
 def upload():

    return send_from_directory('/images','test.jpeg')



 if __name__ == "__main__":
    app.run(port=4555, debug=True)

谢谢

更新:

感谢@ guest271314帮助我修复在其他浏览器上工作的相机捕获。 我重用了原始的Ajax并将其上传到服务器,但收到404错误,但是我不知道如何将图像保存到服务器位置(/ images) 404错误

现在我将处理PHP代码以处理从ajax调用发送的数据,如何在flask中编写类似的代码

<?php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
//send request to ocr 
print $success ? $file : 'Unable to save the file.';
?>

使用navigator.mediaDevices.getUserMedia() .then().catch()

<!DOCTYPE html>
<html>

<head>
</head>

<body onload="init();">
  <h1>Take a snapshot of the current video stream</h1> Click on the Start WebCam button.
  <p>
    <button onclick="startWebcam();">Start WebCam</button>
    <button type="submit" id="dl-btn" href="#" download="participant.jpeg" onclick="snapshot();">Take Snapshot</button>
  </p>
  <video onclick="snapshot();" width=400 height=400 id="video" controls autoplay></video>
  <p>

    Screenshots :
    <p>
      <canvas id="myCanvas" width="400" height="350"></canvas>
    </p>
    <script>
      //--------------------
      // GET USER MEDIA CODE
      //--------------------


      var video;
      var webcamStream;

      function startWebcam() {
        if (navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia(

              // constraints
              {
                video: true,
                audio: false
              }).then(

              // successCallback
              function(localMediaStream) {
                console.log(webcamStream);
                video.src = window.URL.createObjectURL(localMediaStream);
                webcamStream = localMediaStream;
              })
            .catch(
              // errorCallback
              function(err) {
                console.log("The following error occured: " + err);
              })

      } else {
        console.log("getUserMedia not supported");
      }
      }


      //---------------------
      // TAKE A SNAPSHOT CODE
      //---------------------
      var canvas, ctx;

      function init() {
        video = document.querySelector('video');
        // Get the canvas and obtain a context for
        // drawing in it
        canvas = document.getElementById("myCanvas");
        context = canvas.getContext('2d');
      }

      function snapshot() {
        // Draws current image from the video element into the canvas
        console.log(webcamStream);
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        webcamStream.getTracks().forEach(function(track) {
          track.stop();
        });
        var dataURL = canvas.toDataURL('image/jpeg', 1.0);
        document.querySelector('#dl-btn').href = dataURL;

        console.log(dataURL)

      }
    </script>
</body>

</html>

plnkr https://plnkr.co/edit/vuPJRvYZNXLC7rjzKvpj?p=产品目录

暂无
暂无

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

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