How to capture picture from webcam with Webcam.js
It uses HTML5 getUserMedia API to capture the picture. Flash is only used if the browser doesn’t support getUserMedia.
Contents
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:
- 1
98 Comments
Leave a Reply
© 2016-2020 Makitweb, All rights reserved
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
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 –
source
function saveSnap(){
// Get base64 value from
var base64image = document.getElementById(“imageprev”).src;
Webcam.upload( base64image, ‘upload.php’, function(code, text) {
console.log(‘Save successfully’);
console.log(“Image path : ” + text);
});
}
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..
Hi Rachit,
Are you viewing any error in the browser console?
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..
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.
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
Dear Yogesh Singh,
Thanks a lot for help…
now i have done it with your help and guideline..
Thanks a lot once again…
Hi Rachit/ Yogesh,
I am facing the same issue and there is no error in browser please help how to resolve this.
Hi Nitesh,
Have you checked the folder permission?
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
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.
Can you share me your code at makitweb@gmail.com so I can check?
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
Hi Dipali,
Is any error displaying in the browser console? and have you downloaded tutorial code and tried implementation?
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….
Can you share me your code at makitweb@gmail.com so I can check?
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?
Is any error displaying in browser console?
It fails to do anything I click the save button and nothing happens.
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.
The image is still not saving for me. Was the download link updated please?
Yes, I updated the download link and I checked it is working.
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
You can mail me at makitweb@gmail.com
when i click on button images is clicked and shows in below button but how to upload that images into database..
You need to save the image to your server then save the path in your database.
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.
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.
works on localhost but is it working on live server?
Hi Parul,
Yes, it will work on the live server. I already added a demo on the tutorial. It requires https for working.
please help..i am trying this on my project running in localhost.. my images not saved in upload folder.
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.
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.
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.
You’re welcome.
Can I save an image into local folder? Or it is saved locally and I just don’t know where can I find it?
Hi Patrycja,
The file is saved in the project upload directory.
noInterfaceFoundText what is this error mean
Hi Gops,
On which browser you are checking and does error displaying as an alert message or in the browser console.
Webcam.js Error: No supported webcam interface found.
// 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 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.
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?
Hi Tony,
The plugin uses Flash only if the browser doesn’t support getUserMedia. Chrome supports getUserMedia.
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
Hi Ahmed,
I checked it is working. The file is been saved on the server.
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!
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 Aditya,
Can you share the link?
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 Kumaran,
getUserMedia which is needed for camera access is not allowed on Http. The website must be on Https.
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.
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.
it will work on localhost ?
Yes, it will work.
for me its not working fine . The interface is not showing. some error messages are coming like alert after page reload
Hi Ajmal,
What message it is displaying in alert and in which browser are you checking?
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.
Hi Phil,
You are testing it on your local system or server?
Not on a local server. On my web server for domain “philbair.org”
The URL is http://philbair.org/code/camera
I don’t know if you are getting these replies.
Hi Phil,
Camera access only enables in the browser if a site is on HTTPS.
That helps!
Thank you
But is it possible to remove that limitation?
Hi Phil,
It is not a limitation. The browser has changed its security policy. For accessing the microphone, camera requires HTTPS.
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