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

30

How to perform the procedure of capturing the user's webcam image in a registration form to send via POST ? I'm looking for a solution that is compatible with most browsers and is simple to implement.

    
asked by anonymous 05.07.2014 / 19:03

2 answers

23

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 code is summarized in these two files, follow this model as a test factor. Set up your application with jQuery, and a folder named pasta1 , all done in HTML5 with PHP.

In terms of browsers, Google Chrome and Firefox worked perfectly, IE was unsuccessful.

Sources:

06.07.2014 / 00:28
11

There is a very interesting project on GitHub to provide a current solution for using the client webcam, making use of fallback for Flash in cases of older browsers:

WebcamJS

  

WebcamJS is a small (~ 3K mini- and compressed) standalone JavaScript library to capture photos from your computer's camera, and deliver them to you as JPEG or PNG Date 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><divid="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 server

The Webcam.snap() function provides the image via a JavaScript Data URI, 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 just as if we had submitted a form with a <input type="file" name="webcam"> field, so we can simply get 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 you need to send more data to the server along with the image, you can do so by adding the queryString form:

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 detailed and full of use examples in the GitHub link.

    
25.12.2014 / 18:22