通过ajax将摄像头从webcam发送到Flask Server

时间:2017-10-22 22:15:01

标签: javascript jquery python ajax flask

我想拍摄快照表单网络摄像头并通过ajax将其发送到Flask服务器

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

这是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>
&#13;
&#13;
&#13;

这是我的服务器代码: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 error

现在我正在lloking php代码来处理从ajax调用发送的数据,如何在烧瓶中编写类似的代码

<?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.';
?>

1 个答案:

答案 0 :(得分:0)

使用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=catalogue