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


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


Minimum Example



<meta charset="utf-8">
<title>Tirar Fotos</title>
<script src="//"></script>
        video { border: 1px solid #ccc; display: block; margin: 0 0 20px 0; }
        #canvas { margin-top: 20px; border: 1px solid #ccc; display: block; }
    <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>
    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;
            }, errBack);
        } else if(navigator.webkitGetUserMedia) {
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
            }, errBack);
        else if(navigator.mozGetUserMedia) {
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
            }, errBack);
    }, false);
    document.getElementById("snap").addEventListener("click", function() {      
        canvas.getContext("2d").drawImage(video, 0, 0, 640, 480);       
    document.getElementById("save").addEventListener("click", function() {      
        $.post('fotossalvar.php', {imagem:canvas.toDataURL()}, function(data){


    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.


06.07.2014 / 00:28

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


  width: 320,
  height: 240,
  image_format: 'jpeg',
  jpeg_quality: 90

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;
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=""></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>

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

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