How to capture picture from webcam with Webcam.js

Webcam.js is a JavaScript library that allows us to capture a picture from the webcam.

It uses HTML5 getUserMedia API to capture the picture. Flash is only used if the browser doesn’t support getUserMedia.

How to capture picture from webcam with Webcam.js


Table of Content

  1. Download and Include Webcam.js library
  2. Basic Example of Webcam.js
  3. Add sound while Capturing a Picture
  4. Save Image to the Server
  5. Conclusion

1. Download and Include Webcam.js library

  • Download this from GitHub.
  • Include webcam.min.js in the page.
<script type="text/javascript" src="webcamjs/webcam.min.js"></script>

2. Basic Example of Webcam.js

  • Configure

By Webcam.set() function override the default setting. Call Webcam.attach() function on which pass the selector where you want to show live camera view.

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

Just call Webcam.snap() function that has a callback function. The function contains the data_uri that you can use to show a preview or save as an image that generates after taking a snapshot.

Webcam.snap( function(data_uri) {
    // display results in page
    document.getElementById('results').innerHTML = 
     '<img src="'+data_uri+'"/>';
} );

Completed Code

<!-- CSS -->
<style>
#my_camera{
     width: 320px;
     height: 240px;
     border: 1px solid black;
}
</style>

<div id="my_camera"></div>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
 
<div id="results" ></div>
 
<!-- Webcam.min.js -->
<script type="text/javascript" src="webcamjs/webcam.min.js"></script>

<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
     width: 320,
     height: 240,
     image_format: 'jpeg',
     jpeg_quality: 90
});
Webcam.attach( '#my_camera' );

<!-- Code to handle taking the snapshot and displaying it locally -->
function take_snapshot() {
 
    // take snapshot and get image data
    Webcam.snap( function(data_uri) {
        // display results in page
        document.getElementById('results').innerHTML = 
          '<img src="'+data_uri+'"/>';
    } );
}
</script>

View Demo


3. Add sound while Capturing a Picture

Create an Object of Audio() class and specify audio file and call play() method when the user clicks on the button to capture a picture.

Completed Code

<!-- CSS -->
<style>
#my_camera{
    width: 320px;
    height: 240px;
    border: 1px solid black;
}
</style>

<!-- -->
<div id="my_camera"></div>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
 
<div id="results" ></div>
 
<!-- Script -->
<script type="text/javascript" src="webcamjs/webcam.min.js"></script>

<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">

 // Configure a few settings and attach camera
 Webcam.set({
     width: 320,
     height: 240,
     image_format: 'jpeg',
     jpeg_quality: 90
 });
 Webcam.attach( '#my_camera' );

 // preload shutter audio clip
 var shutter = new Audio();
 shutter.autoplay = true;
 shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';

function take_snapshot() {
    // play sound effect
    shutter.play();

    // take snapshot and get image data
    Webcam.snap( function(data_uri) {
         // display results in page
         document.getElementById('results').innerHTML = 
             '<img src="'+data_uri+'"/>';
    });
}
</script>

4. Save Image to the Server

Store the generated value while taking the snapshot in a variable or element and call Webcam.upload() method for saving.

The method takes 3 parameters –

  • Generated base64 value
  • Action URL ( for handling the value and saving to the directory )
  • Callback function ( For handling response )
Webcam.upload( base64image, 'upload.php', function(code, text) {
 
});

HTML & Script

Create three buttons –

  • 1st to configure the webcam,
  • 2nd to take the snapshot, and
  • 3rd for the save snapshot to the server.
<!-- CSS -->
<style>
#my_camera{
    width: 320px;
    height: 240px;
    border: 1px solid black;
}
</style>

<!-- -->
<div id="my_camera"></div>
<input type=button value="Configure" onClick="configure()">
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type=button value="Save Snapshot" onClick="saveSnap()">
 
<div id="results" ></div>
 
<!-- Script -->
<script type="text/javascript" src="webcamjs/webcam.min.js"></script>

<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
 
// Configure a few settings and attach camera
function configure(){
    Webcam.set({
        width: 320,
        height: 240,
        image_format: 'jpeg',
        jpeg_quality: 90
    });
    Webcam.attach( '#my_camera' );
}
// A button for taking snaps

// preload shutter audio clip
var shutter = new Audio();
shutter.autoplay = false;
shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';

function take_snapshot() {
    // play sound effect
    shutter.play();

    // take snapshot and get image data
    Webcam.snap( function(data_uri) {
        // display results in page
        document.getElementById('results').innerHTML = 
           '<img id="imageprev" src="'+data_uri+'"/>';
    } );

    Webcam.reset();
}

function saveSnap(){
    // Get base64 value from <img id='imageprev'> source
    var base64image = document.getElementById("imageprev").src;

    Webcam.upload( base64image, 'upload.php', function(code, text) {
         console.log('Save successfully');
         //console.log(text);
    });

}
</script>

PHP (upload.php)

Create an upload.php file for uploading a file and upload folder to store files. Access file using webcam key – $_FILES['webcam'].

<?php

// new filename
$filename = 'pic_'.date('YmdHis') . '.jpeg';

$url = '';
if( move_uploaded_file($_FILES['webcam']['tmp_name'],'upload/'.$filename) ){
     $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/upload/' . $filename;
}

// Return image url
echo $url;

5. Conclusion

Call Webcam.attach() function to show the live camera view in the element and to take the snapshot call Webcam.snap() which gives you base64 format value as a response that you can use to show a preview or you can save it as an image on the server.

According to the Offical documentation, WebcamJS has been tested on the following browsers/operating systems:

OS Browser Notes
Mac OS X Chrome 30+ Works — Chrome 47+ requires HTTPS
Mac OS X Firefox 20+ Works
Mac OS X Safari 6+ Requires Adobe Flash Player
Windows Chrome 30+ Works — Chrome 47+ requires HTTPS
Windows Firefox 20+ Works
Windows IE 9 Requires Adobe Flash Player
Windows IE 10 Requires Adobe Flash Player
Windows IE 11 Requires Adobe Flash Player
If you found this tutorial helpful then don't forget to share.