How to capture a photo through the user’s webcam and send via POST?

Asked

Viewed 22,530 times

30

How to perform the user’s webcam image capture procedure on a registration form to submit via POST? I am looking for a solution that is compatible with most browsers and that is simple to implement.

2 answers

24

Minimum Example

PHP

camera.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tirar Fotos</title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<style>
        video { border: 1px solid #ccc; display: block; margin: 0 0 20px 0; }
        #canvas { margin-top: 20px; border: 1px solid #ccc; display: block; }
</style>
</head>
<body>
<div>
    <div><video id="video" width="640" height="480" autoplay></video></div>
    <div><button id="snap">Tirar Foto</button></div>
    <div><button id="save">Salvar Foto</button></div>
    <div><canvas id="canvas" width="640" height="480"></canvas></div>
<script>
    window.addEventListener("DOMContentLoaded", function() {
        var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        video = document.getElementById("video"),
        videoObj = { "video": true },
        errBack = function(error) {
                console.log("Video capture error: ", error.code); 
        };  
        if(navigator.getUserMedia) {
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) {
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        }
        else if(navigator.mozGetUserMedia) {
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        }
    }, false);
    document.getElementById("snap").addEventListener("click", function() {      
        canvas.getContext("2d").drawImage(video, 0, 0, 640, 480);       
        //alert(canvas.toDataURL());
    });
    document.getElementById("save").addEventListener("click", function() {      
        $.post('fotossalvar.php', {imagem:canvas.toDataURL()}, function(data){
        },'json');
    });
</script>    
</body>
</html>

fotossalvar.php

<?php
    function base64_to_jpeg( $base64_string, $output_file ) {
        $ifp = fopen( $output_file, "wb" ); 
        fwrite( $ifp, base64_decode( $base64_string) ); 
        fclose( $ifp ); 
        return( $output_file ); 
    }       
    $imagem = str_replace('data:image/png;base64,','',$_POST['imagem']);        
    base64_to_jpeg($imagem, "pasta1/foto1.png");        
    echo json_encode(array('imagem' => 1));

All the code comes down to these two files, follow this template as a test factor. Configure your application with jQuery, and a folder named after pasta1, everything is done in HTML5 with PHP.

In relation to browsers, the Google Chrome and the Firefox worked perfectly, already the IE did not succeed.

Sources:

11

There is a very interesting project on Github to provide a current solution for the client’s webcam usage, making use of Flash fallback in older browser cases:

Webcamjs

Webcamjs is a small (~3K minified and compressed) library standalone in Javascript to capture photos from your computer’s camera, and deliver them to you as JPEG or PNG Data Uris. Images can be displayed on your web page, rendered on a screen, or submitted to your server. Webcamjs uses HTML5 getUserMedia, but provides an automatic and invisible fallback through Adobe Flash.

Demonstration

Webcam.set({
  width: 320,
  height: 240,
  image_format: 'jpeg',
  jpeg_quality: 90
});
Webcam.attach('#my_camera');

function take_snapshot() {
  // take snapshot and get image data
  Webcam.snap(function(data_uri) {
    // display results in page
    document.getElementById('results').innerHTML =
      '<h2>Here is your image:</h2>' +
      '<img src="' + data_uri + '"/>';
  });
}
body {
  font-family: Helvetica, sans-serif;
}
h2,
h3 {
  margin-top: 0;
}
form {
  margin-top: 15px;
}
form > input {
  margin-right: 15px;
}
#results {
  float: right;
  margin: 20px;
  padding: 20px;
  border: 1px solid;
  background: #ccc;
}
		
<script src="http://pixlcore.com/demos/webcamjs/webcam.js"></script>
<div id="results">A imagem capturada aparece aqui...</div>

<h1>WebcamJS Página de teste</h1>
<h3>Demonstração de uma captura e apresentação em 320x240</h3>

<div id="my_camera"></div>

<form>
  <input type=button value="Tirar Snapshot" onClick="take_snapshot()">
</form>

Send to the server

The function Webcam.snap() provides the image via a URI Data via Javascript, as we saw in the example above.

However, we also have a way to decode and send this image data to the server via an AJAX call:

var data_uri = Webcam.snap();

Webcam.upload( data_uri, 'meuScript.php', function(code, text) {
    // Upload concluído
    // 'code' contém o código da resposta HTTP enviado pelo servidor, ex. 200
    // 'text' contem o que o servidor enviou
});

On the server side, the data arrives as if we had submitted a form with a field <input type="file" name="webcam">, so we can simply receive the image as follows:

// verificações de segurança e outros
// ...
// mover o ficheiro recebido para o local pretendido
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');

If it is necessary to send more data to the server along with the image, we can do so by adding them in the form of queryString:

var username = 'Bubu';
var image_fmt = 'jpeg';
var url = 'meuScript.php?username=' + username + '&format=' + image_fmt;
Webcam.upload( data_uri, url, function(code, text) {...} );

Note: There are many options provided by the Webcamjs project and it is very well detailed and packed with examples of use in the link of the same in Github.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.