How to capture picture from webcam with Webcam.js

Skip to content

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


Contents

  1. Download and Include
  2. Basic Example
  3. Add sound
  4. Save Image
  5. Conclusion

1. Download and Include

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

2. Basic Example

  • 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 which 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>

3. Add sound

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

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 – One to configure the webcam, second the take the snapshot and third for the save.

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

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

Related posts:

How to Get Records from Database with AngularJS in CodeIgniter
Show Notification, prompt, and confirmation with Overhang.js
Restrict keyboard character input with jQuery
Spread the love
  • 1

98 Comments

  1. Very well written but dont you think flash is almost gone now.

    September 20, 2017

    Reply

  2. pavan said:

    How to convert Data URI of image into normal URL which is required to send for face detection?

    April 2, 2018

    Reply

    • pavan said:

      Actually face detection API is expecting normal http URL instead of data URI

      April 2, 2018

      Reply

      • Hi Pavan,
        You can look at the 4th point – Save Image to save an image to a folder.

        Here, you get the upload image path in the saveSnap() function –
        function saveSnap(){
        // Get base64 value from  source
        var base64image = document.getElementById(“imageprev”).src;

        Webcam.upload( base64image, ‘upload.php’, function(code, text) {
        console.log(‘Save successfully’);
        console.log(“Image path : ” + text);
        });

        }

        April 3, 2018

        Reply

        • Rachit said:

          Dear Yogesh Singh,
          Your Fourth no. function saveSnap() is not working. its not saving image in upload folder..
          please help me…
          if you can assist me so please assist..

          April 20, 2019

          Reply

          • Hi Rachit,
            Are you viewing any error in the browser console?

            April 21, 2019
          • Rachit said:

            Dear Yogesh Singh,
            thanks a lot.. Your code is properly running now.
            but there is a problem, i want to send input text value also to php page with image but i could not. please help me.
            And tell me, how can i send input text value in php with save image with your this code..
            i want to registerd my name and image in database table..

            April 21, 2019
          • You need to pass the value using AJAX page url like – upload.php?name=yogesh. Currently, it only allows passing values from URL only not by a POST request.

            April 21, 2019
          • Rachit said:

            Dear Yogesh Singh,
            Good Morning.
            Can You provide me a complete code
            in which, i can pass image and text value in upload.php page to store in database please..
            actually its really urgent for me..
            please…..
            my email id ::
            rachit3749@gmail.com

            April 22, 2019
          • Rachit said:

            Dear Yogesh Singh,
            Thanks a lot for help…
            now i have done it with your help and guideline..
            Thanks a lot once again…

            April 22, 2019
          • Nitesh said:

            Hi Rachit/ Yogesh,

            I am facing the same issue and there is no error in browser please help how to resolve this.

            May 25, 2020
          • Hi Nitesh,
            Have you checked the folder permission?

            May 27, 2020
          • Nitesh said:

            Hi Yogesh/Rachit,

            Facing the same issue saveSnap() function is not working for me.
            please help me on this.
            if possible please provide the full code

            May 26, 2020
  3. GANGADHAR JADHAV said:

    how to implement same code in Angular 4 or 2

    May 26, 2018

    Reply

  4. April said:

    Why do I click a button save snap. But it does not show and save picture anything.

    October 19, 2018

    Reply

      • Dipali said:

        Hi Yogesh,

        I am also struggling to save image as per #4. Send details over the email as well.
        Any help would be appreciated.

        Thanks

        February 12, 2020

        Reply

        • Hi Dipali,
          Is any error displaying in the browser console? and have you downloaded tutorial code and tried implementation?

          February 12, 2020

          Reply

  5. A said:

    thank you

    October 20, 2018

    Reply

  6. Markus said:

    How i can change the Name of the file via <input Form ?

    November 21, 2018

    Reply

  7. ninos said:

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

    November 22, 2018

    Reply

  8. Sarah Ciantar said:

    I’m having issues to get the image to save…. is there something else we need to do in order to get it to work please?

    February 6, 2019

    Reply

    • Is any error displaying in browser console?

      February 6, 2019

      Reply

  9. Sarah Ciantar said:

    It fails to do anything I click the save button and nothing happens.

    February 6, 2019

    Reply

    • I checked the tutorial demo which is also not working because of webcam.js library update. I am using the older version in the example.

      Updated the tutorial and download link. You can download the example and test it again.

      February 6, 2019

      Reply

  10. Sarah Ciantar said:

    The image is still not saving for me. Was the download link updated please?

    February 7, 2019

    Reply

    • Yes, I updated the download link and I checked it is working.

      February 7, 2019

      Reply

  11. Sarah Ciantar said:

    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 ?

    February 8, 2019

    Reply

      • paul said:

        when i click on button images is clicked and shows in below button but how to upload that images into database..

        March 12, 2019

        Reply

        • You need to save the image to your server then save the path in your database.

          March 12, 2019

          Reply

  12. santosh said:

    how to call webcam in typescript file.
    any suggestion

    February 12, 2019

    Reply

  13. Chandra Sekhar said:

    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

    February 26, 2019

    Reply

  14. Sridhar said:

    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.

    February 26, 2019

    Reply

  15. Sridhar said:

    on IE 10 & 11, getting Webcam is undefined, unable to test. Any suggestions on this.

    February 27, 2019

    Reply

    • Hi Sridhar,
      I checked it on IE 11 and it is working fine. It requires Adobe flash player to access webcam in the IE browser.

      February 27, 2019

      Reply

  16. parul said:

    works on localhost but is it working on live server?

    March 22, 2019

    Reply

    • Hi Parul,
      Yes, it will work on the live server. I already added a demo on the tutorial. It requires https for working.

      March 23, 2019

      Reply

  17. parul said:

    please help..i am trying this on my project running in localhost.. my images not saved in upload folder.

    March 23, 2019

    Reply

  18. Deekay said:

    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.

    April 2, 2019

    Reply

    • Currently, the plugin not allows selecting the camera. It only asks for camera access permission from the browser. It is depending on the browser which camera is been accessed.

      April 3, 2019

      Reply

  19. kirti said:

    Please Help me to do this

    April 16, 2019

    Reply

  20. Seongmook LIM said:

    Hello~
    I sent an email for my error message.
    Please check your mailbox.

    April 19, 2019

    Reply

  21. SEONGMOOK LIM said:

    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,

    April 22, 2019

    Reply

    • SEONGMOOK LIM said:

      Thanks

      I did it!!!
      I installed php7 on my windows10 desktop
      Thanks

      April 22, 2019

      Reply

  22. Ulrich said:

    Hello
    How can i stop the webcam programmaticaly when i finished to take a photo?

    May 1, 2019

    Reply

  23. Mats Montelin said:

    Hello again!

    I meen, that picture do not save to the upload mapp.

    May 11, 2019

    Reply

  24. juan caballero said:

    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

    May 23, 2019

    Reply

  25. Wisdom Kwaku Deku said:

    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

    May 27, 2019

    Reply

  26. hasan said:

    can i snap using rear camera?
    if it can,how the code

    May 28, 2019

    Reply

  27. Avinash said:

    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.

    July 16, 2019

    Reply

  28. Prajeesh said:

    Can we implement crop functionality?

    July 19, 2019

    Reply

  29. Godwin P said:

    in PHP where I have to give server URL to upload an image to the server.

    August 6, 2019

    Reply

  30. david potter said:

    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

    August 12, 2019

    Reply

    • sean said:

      do you really want to store the image in a a database?

      August 17, 2019

      Reply

  31. sean said:

    Brilliant article, really helpful. Code example works perfectly. Thanks for your efforts.

    August 17, 2019

    Reply

  32. Patrycja said:

    Can I save an image into local folder? Or it is saved locally and I just don’t know where can I find it?

    August 30, 2019

    Reply

    • Hi Patrycja,
      The file is saved in the project upload directory.

      August 31, 2019

      Reply

  33. Gops said:

    noInterfaceFoundText what is this error mean

    September 3, 2019

    Reply

    • Hi Gops,
      On which browser you are checking and does error displaying as an alert message or in the browser console.

      September 4, 2019

      Reply

      • Levi Garcia said:

        Webcam.js Error: No supported webcam interface found.

        October 1, 2019

        Reply

  34. Patrick Kohli said:

    // 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”).

    September 15, 2019

    Reply

  35. Pat Kohli said:

    Please disregard. I stepped back on my version to align with your and the problem went away.

    September 15, 2019

    Reply

  36. Cem Atilkan said:

    I was wondering if there is a way to draw a rectangle on the video let’s say 128px by 128px. Is it possible?

    October 10, 2019

    Reply

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

    October 22, 2019

    Reply

    • Hi Tony,
      You can do this by adding – ‘constraints’,{ facingMode:’environment’ } in Webcam.set();

      Example –
      Webcam.set(‘constraints’,
      { facingMode:’environment’ },{
      width: 320,
      height: 240,
      image_format: ‘jpeg’,
      jpeg_quality: 90,

      });

      I checked it is working.

      October 22, 2019

      Reply

    • Arunkumar T said:

      HI…
      For me localhost working but its not work for IP address.
      can you please share your code to arun.mca22@gmail.com

      November 24, 2019

      Reply

  38. Adobe Flash will no longer be supported by Google Chrome next year. Is this code dependent on flash to run?

    October 22, 2019

    Reply

    • Hi Tony,
      The plugin uses Flash only if the browser doesn’t support getUserMedia. Chrome supports getUserMedia.

      October 22, 2019

      Reply

  39. Ahmed said:

    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

    October 23, 2019

    Reply

    • Hi Ahmed,
      I checked it is working. The file is been saved on the server.

      October 25, 2019

      Reply

      • Ahmed said:

        Hi Yogesh,

        Sorry i’m new to PHP and was the reason I couldn’t get the files to work.

        I want to ask you 1 last question. How do you give the file a name through a input field before saving it? I’m struggling with the php part.

        Thanks for the code btw!

        October 28, 2019

        Reply

  40. CoolGuy said:

    Could you please help me to make it work in windows 7 & 8?

    Its working in IE 11 in windows 10

    October 25, 2019

    Reply

  41. Aditya said:

    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.

    November 24, 2019

    Reply

  42. Kumaran said:

    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?

    December 2, 2019

    Reply

    • Hi Kumaran,
      getUserMedia which is needed for camera access is not allowed on Http. The website must be on Https.

      December 3, 2019

      Reply

  43. Ankit said:

    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.

    January 3, 2020

    Reply

    • Hi Ankit,
      You can store captured image base64 value in your form hidden field and also you can use it show preview. On form submit read the hidden field value and save it in your server.

      January 4, 2020

      Reply

  44. ajmal said:

    it will work on localhost ?

    January 28, 2020

    Reply

  45. ajmal said:

    for me its not working fine . The interface is not showing. some error messages are coming like alert after page reload

    January 28, 2020

    Reply

    • Hi Ajmal,
      What message it is displaying in alert and in which browser are you checking?

      January 28, 2020

      Reply

  46. Phil said:

    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.

    March 4, 2020

    Reply

    • Hi Phil,
      You are testing it on your local system or server?

      March 6, 2020

      Reply

        • Hi Phil,
          Camera access only enables in the browser if a site is on HTTPS.

          March 7, 2020

          Reply

          • phil bair said:

            That helps!

            Thank you

            March 9, 2020
          • phil bair said:

            But is it possible to remove that limitation?

            March 9, 2020
          • Hi Phil,
            It is not a limitation. The browser has changed its security policy. For accessing the microphone, camera requires HTTPS.

            March 10, 2020
  47. RAGU said:

    Ip address cross domain url not working webcam

    March 6, 2020

    Reply

  48. venkat said:

    Dear Yogesh Singh,
    Good Morning.
    Can You provide me a complete code for to run on Java..
    please…..
    my email id ::
    venkat.yembuluru@gmail.com

    May 8, 2020

    Reply

  49. jhonsen dave said:

    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 ?

    May 13, 2020

    Reply

  50. CHAKRAVARTHI KOLIKIPAMULA said:

    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

    May 27, 2020

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *