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.

140 thoughts on “How to capture picture from webcam with Webcam.js”

  1. Thank you for sharing your code.
    I have been trying to use your code to implement another logic of allowing a person to enter a name of the picture taken and save it on the database.
    in short, I created an input field type=text and database table has name and image_url.
    The problem is that I can save the url bt the text field value does not appear.
    How can I go about it.
    Thank you….

    Reply
  2. Do you have an email I can contact you on as I can’t manage to get it to work I updated the script and now not even even the photo capture is working šŸ™

    Reply
  3. Hi Yogesh,

    Thanks for giving us some heads up and detail oriented steps. But, I am having an issue. I am testing it from my laptop which has a inbuilt webcam and my application needs an external webcam. For the first time when we run the application it picks the external webcam and once we save the image after capturing and next time onwards the camera source is changed to inbuilt webcam instead of external. In the code do we have any option to specify which webcam to select? This would be of a great help.

    Thanks,
    Chandra and Sridhar

    Reply
  4. Hi Yogesh, Nice info. But, tts not working in IE 10/11 on Win 7 & 10, getting Webcam is undefined error and not detecting external usb webcam. Any work around for IE browsers? Greatly appreciated, if any suggestions on this.

    Reply
  5. Is there a way to determine which Camera we can use? My Windows 10 Tablet has a Front and a Back Camera and I want to be able to let the User choose which one they take Pictures from.

    Reply
  6. Hello~

    I run your code in the localhost with apache server
    but, the picture didn’t save in the server
    Which part do I have to check?
    I don’t have any error console log.
    I have only “Save successfully” log.

    Thanks,

    Reply
  7. hola, estoy realizando un proyecto jsf + primefaces + postgresql en un servidor web glassfish levante el proyecto a una ip publica mi servidor fisico no tiene camara web y al llamar desde la ip desde mi celular u otra pc con camara web no funciona, solo si mi servidor fisico tiene webcam funciona que puedo hacer

    Reply
  8. This is a nice tutorial. I am building an ASP web page using Access Database as my backend. How do I save such an image into the Access Database using classic asp? I will be grateful if anyone can be of help.

    Thank you

    Reply
  9. Hi Yogesh. I am using the code in my project everything is works well thanks for saving my time by writing lines of code. But I am facing an issue with uploading an image to server using IOS should i have to add anything in the code extra…?
    Again thanks.

    Reply
  10. I am using vb.net and ia ma using visual studio 2019.
    The ‘Configure’ and the “take Snapshot’ buttons work but the Save Snapshot doesn’t work.
    I copied the PHP code to my program but I don’t think it works with asp.net

    I just want to save the picture in a table with a field called photo which is an ‘image’ field.
    I have been working solid for over a week to try to get this to work.
    How can i save the picture to my table.
    thanks so much.
    dave

    Reply
  11. // Thanks!
    // I get an error in my saveSnap() function:
    function saveSnap(){
    // Get base64 value from source
    var base64image = document.getElementById(“imageprev”).src;
    // My error reads
    >> GetPic6.js:37 Uncaught TypeError: Cannot read property ‘src’ of null
    // I am inferring it is the .src member of document.getElementById(“imageprev”).

    Reply
  12. Hi. Your code is working properly both on localhost and in live server. It works on my webcam and my android phone as well. I did a little tweak to alert me that the image file has been saved (example3.html). However, what will I do to change the default camera (ANDROID PHONE) from front to rear?

    Reply
  13. Save snapshot not working

    Is the code up to date? I’ve tried dl the project. The config & take snapshot works but not the save snapshot

    Reply
  14. Hi,

    I tried to implement webcam.js in my project, when I tried in local with eclipse it was working fine. But when I deploy in JBoss 6.3 server it is showing an alert as “Webcam.js Error : No supported webcam interface found”. Kindly help me on this. I don’t know why it is not detecting after deployment in the server.

    Reply
  15. Hi Yokesh.
    Thanks a lot for this wonderful creation.
    I am using this in my project but specifically in chrome browser it is blocking the webcam’s access Because of my server running on http. Do you have any suggestion to rectify this issue?

    Reply
  16. Hi Yogesh,

    I have a File type element in my form. Along with upload option I also want to give alter option to capture live photo and attach in form (In File type element) and the captured image will get posted to server along with other form elements on form submit.

    Could you please help me on this.

    Reply
  17. Hi Yogesh,

    What is the problem when I get an error that says: Webcam.js Error: No supported webcam interface found?

    It works when I pull up your on-line demo, but I get this error when I use it on my own page.

    Reply
  18. can i ask questions? this webcam features can captured image using your wink ? everyone please help me if its possible to webcam ?? to captured image using your wink on your eyes to take selfie and save using web cam ?

    Reply
  19. var base64image = document.getElementById(“data_url”).src;
    Webcam.upload(base64image, ‘./aspiration/upload’,function(code,text) {
    console.log(‘save successfully’)
    console.log(text)
    Here i am sending the url to controller .but it is showing an error(connot read property of src of null

    Reply
  20. First, thank you very much for your effort, the solution works really good! Anyway I have a weird problem. When running demo link you put here on Firefox at macOS (newest) it works using HTML5 which I desire. While running your sample code on my localhost on the same browser, just in new tab (w/out https) it always uses Flash which I would like to avoid. What could be the reason? is there some option to force HTML5 instead?

    Reply
  21. Thanks for sharing the code. It help me alot. I’ve question kindly tell me is there is function to close webcam just like webcam.set because we have to close webcam just after using it. Opening webcam for long time taking power consumption. Thanks in advance.

    Reply
  22. Hi, I am trying to implement this on MVC and C#, the problem I have is the DataURI I pass to the controller can’t be saved as a JPG. I need to save it as a JPG and the samples I found related with the implementation of this library only save the DataURI string as is into a txt file. I need to generate a standard JPG file. Do you have by chance any approach? I really would appreciate any help. Thanks in advance.

    Reply
    • Please can anyone help ? I’m still stuck the image keeps automatically rotating 90 degrees on attaching the image to preview and save.

      Reply
  23. Hi Sir,
    As Project is not supporting PHP .I want to implement above code completely in Javascript without Php .Could you please help me out for this.Thank you in advance.

    Reply
  24. Hello Sir,

    Thank you so much for providing us with this solution, You are blessed.
    Although I am having some trouble figuring a solution for storing more than one image at once. I’m trying an array but i need to host it on a cpanel to see if the php works well because of directory format on windows. I would be grateful if you could send a working example of your code saving multiple snapshots, thank you.

    Reply
  25. hi, i have done the code and its working but i wanted to capture image without showing the video is there any way to do it because i’m creating quiz website and wanted to click image on every question without showing the video.

    Reply
  26. Thanks for this solution.. I have one request..

    When capturing a larger photo on an iPhone (width & height) can the displayed results be at a different size?

    Many thanks
    Alan

    Reply
  27. camera work very well on localhost pc as a server. but client cant access camera. webcam.js not found supported camera. client already installed webcam. how fix it. even on mobile device i can access my camera in your demo page on this site. thankyou

    Reply
  28. Sir, I have used your code and everything is working fine, thank you. But, my camera screen gets split-ed into two or three parts while capturing image. Can you please help. The code is same as u have posted.

    Reply
  29. Hello, I used your code, however it does not show camera feed, also do not ask for permission to use camera. Please help

    Reply
  30. Hi. I really appreciate your work.. I am wishing to load the webcam automatically in full screen mode when page is loaded for a small home project. Can you please provide solution to handle this. Thank You !!!

    Reply
  31. Thanks a lot for your tutorial, it’s working but there is a problem
    when i take a picture from laptop webcam it is ok
    when i take a picture from smartphone it isn’t ok
    in the code, the width is 320 and the height: 240
    in the detail
    the cam of the smartphone is well displayed, but when i take the snapshot the image is stretched !
    it is because in the smartphone, the width is lesser than the hight, so the snapshot displays a stretched image that i cannot use
    what i am looking for is to have the snapshot takes an image as it is in the camera without stretching it to the specified width
    if i change the width to 180, all appears ok, but i want it to works in all situations, i cannot change the resolution depending on each users devices
    Thank You

    Reply
  32. Hi
    Thanks for your tutorial
    i don’t know if you got my first message or not
    for me, when taking photo from smartphone where the width is lesser than the height, the image generated by the snapshot is stretched so unusable
    can you help me please ?
    Thank You

    Reply
  33. Hi Yoges
    Thanks for a brilliant tutorial. I have seen a few examples online but this is the best and the only one I found that works! Do you have a tutorial on how to save the image to a database as well as saving to the uploads folder?

    Reply
  34. Hello,
    Thank you for sharing your code, I would like to know if there is a way to improve the picture quality. I’ve tried different widths and heights but the pictures is always kind of blurry.
    Thank you for your help.

    Reply

Leave a Comment