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.

Table of Content
- Download and Include Webcam.js library
- Basic Example of Webcam.js
- Add sound while Capturing a Picture
- Save Image to the Server
- Conclusion
1. Download and Include Webcam.js library
- Download this from GitHub.
- Include
webcam.min.jsin 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>
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 |
Very well written but dont you think flash is almost gone now.
How to convert Data URI of image into normal URL which is required to send for face detection?
Actually face detection API is expecting normal http URL instead of data URI
how to implement same code in Angular 4 or 2
Why do I click a button save snap. But it does not show and save picture anything.
thank you
How i can change the Name of the file via <input Form ?
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….
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?
It fails to do anything I click the save button and nothing happens.
The image is still not saving for me. Was the download link updated please?
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 š
how to call webcam in typescript file.
any suggestion
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
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.
on IE 10 & 11, getting Webcam is undefined, unable to test. Any suggestions on this.
works on localhost but is it working on live server?
please help..i am trying this on my project running in localhost.. my images not saved in upload folder.
Hi Parul,
so did you get it running on localhost?
thx š
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.
Please Help me to do this
Hello~
I sent an email for my error message.
Please check your mailbox.
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,
Thanks
I did it!!!
I installed php7 on my windows10 desktop
Thanks
Hello
How can i stop the webcam programmaticaly when i finished to take a photo?
Hi,
Saw your code online and would test this. When I take a picture, nothing happens.
If you look at it then I would be happy.
Look here: http://www.bildnet.info/Booking/index.php
Hello again!
I meen, that picture do not save to the upload mapp.
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
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
can i snap using rear camera?
if it can,how the code
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.
Can we implement crop functionality?
Not Working on localhost replacing localhost to IP address, like http://172.30.50.237/takephoto but working fine if http://localhost/takephoto
in PHP where I have to give server URL to upload an image to the server.
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
do you really want to store the image in a a database?
Brilliant article, really helpful. Code example works perfectly. Thanks for your efforts.
Can I save an image into local folder? Or it is saved locally and I just don’t know where can I find it?
noInterfaceFoundText what is this error mean
// 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”).
Please disregard. I stepped back on my version to align with your and the problem went away.
I was wondering if there is a way to draw a rectangle on the video let’s say 128px by 128px. Is it possible?
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?
HI…
For me localhost working but its not work for IP address.
can you please share your code to arun.mca22@gmail.com
Adobe Flash will no longer be supported by Google Chrome next year. Is this code dependent on flash to run?
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
Could you please help me to make it work in windows 7 & 8?
Its working in IE 11 in windows 10
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.
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?
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.
it will work on localhost ?
for me its not working fine . The interface is not showing. some error messages are coming like alert after page reload
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.
Ip address cross domain url not working webcam
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
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 ?
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
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?
Hello, Can i pass a php value to name the file? rather than using hour min, seconds? from first page
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.
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.
Code is not work on IP address
please provide me solution
In IE 11 i got this error
SCRIPT1010: Se esperaba un identificador
webcam.min.js (2,5621)
Any Suggestion ?
has anyone had an issue with the image captured is appearing sideways and not up right.
Please can anyone help ? I’m still stuck the image keeps automatically rotating 90 degrees on attaching the image to preview and save.
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.
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.
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.
hallo, this is work for me. what should i do if click saveSnap i want to
more than one image is stored.
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
HIā¦
For me localhost working but its not work for IP address.
can you please share your code to arif.websolution@gmail.com
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
I implemented it and it’s working fine. Now I want to capture IRIS (eye). So how should I zoom the webcam?
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.
Hello, I used your code, however it does not show camera feed, also do not ask for permission to use camera. Please help
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 !!!
Thank you so much! My webcam capture is now working and I can use the data uri for saving the image file! Great work
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
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
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?
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.
Hi. Its working on my android phone. How to use the back camera as a default instead of the front camera?
How can I set the Webcam size to 400 by 400?, only the output image is changing, not the webcam