简体   繁体   中英

How to save image captured from webcam to folder

I am working on a Django web application. In this application a user can trigger their webcam and capture a photo with a press of a button. This photo should then be saved to the server.

The problem I am facing is, I am not able to save the photo. This is my code so far

<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>

// Grab elements, create settings, etc.
var video = document.getElementById('video');

// Get access to the camera!
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({
        video: true
    }).then(function(stream) {
        //video.src = window.URL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    });
}

// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');

// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
    context.drawImage(video, 0, 0, 640, 480);
});

With this code I am able to snap a picture into a canvas but I am stuck trying to save this to the server folder. on some research, I figured this is not possible only with javascript and that I will be requiring a scripting lauguage like python or php. Since I am using django, python seems like a better option here. But I am not sure how to do this.

Please help me

Thank you

If you want to save your image on backend, you need to first send the image data from the browser to the backend. After you have displayed image on canvas you can get the image data in Base64 String format by this:

document.getElementById("snap").addEventListener("click", function() {
  context.drawImage(video, 0, 0, 640, 480);

  // get image data as string
  const imageString = canvas.toDataURL();

  // send image to server
  fetch('/image/save', {
    method: "POST",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
      imageString: imageString, 
    }),
  })
});

and then on your server, you need to define the image save route, convert Base64 Image string to Image file and then save it to filesystem.

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