简体   繁体   中英

Send imageObject from webcam by ajax to Flask Server

I want to take the snapshot form webcam and send it by ajax to the Flask server

I have the upload.html taking the snapshot from webcam and and send it through ajax, but I do not know much about Flask server to get data from Ajax and save it on the specific location (/images)

Here is the upload.html. The Webcam work on Firefox only (not working in Chrome). These other browsers I haven't tested yet

  //-------------------- // 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> 

Here is my server code: 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)

Thanks

Updated:

Thanks for @guest271314 help me fix the camera capture working on other browser. I reused my original ajax and upload it to server , but get the 404 error, but I do not know how to save image to server location (/images) 404 error

Now I am lloking the php code to handle data sent from ajax call, how to write the similar code in 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.';
?>

Use navigator.mediaDevices.getUserMedia() , .then() and .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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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