Capture Image using Javascript Webcam API

In this Tutorial we are using webcam.js jQuery Plugin to Capture Image Using JavaScript Webcam API and Upload it on Web Server.

We all like to upload selfie on social networking websites like Facebook,Twitter,Instagram or Google+ and as a programmer we would have such kind of features on our websites too.I was working on a social Networking Website design and I think that it must have a Webcam so I added an webcam using jpegwebcam (webcam.js) by Joseph Huckaby.

View DemoDownload

Note: This Demo will not work in Chrome Browser because chrome is asking to have a https website to access webcam.

Javascript Webcam

Below are some steps about how you can insert Webcam on your website using javascript webcam api.

Step 1: Download the Javascript webcam.

Step 2: Include the webcam.js script on your page.

<script src="webcam.js" type="text/javascript"></script>

OR

Your Page should look like…

<!-- Head Contents Goes here -->
<!-- Body Contents Goes here -->
<script src="webcam.js" type="text/javascript"></script>

Step 3:Attach the Webcam on your page.

[moptin id="3100"]

<div id="my_camera"></div>

	<!-- A button for taking snaps -->

<form>
		<input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
	</form>

	<!-- 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' );
		function take_snapshot() {
			// take snapshot and get image data
			Webcam.snap( function(data_uri) {
				// display results in page
				document.getElementById('results').innerHTML = 
					'
<h2>Here is your image:</h2>

' + 
					'<img src="'+data_uri+'"/>';
                                Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                            // Upload complete!
                                            // 'code' will be the HTTP response code from the server, e.g. 200
                                            // 'text' will be the raw response content
                                });
			} );
		}
	</script>

OR

Your Page content should look like..


<div id="my_camera"></div>

	<!-- A button for taking snaps -->
	<a href="#" onclick="take_snapshot()">Take Snapshot</a>
	<script type="text/javascript" src="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' );
		function take_snapshot() {
			// take snapshot and get image data
			Webcam.snap( function(data_uri) {
				// display results in page
				document.getElementById('results').innerHTML = 
					'
<h2>Here is your image:</h2>

' + 
					'<img src="'+data_uri+'"/>';
                                Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                            // Upload complete!
                                            // 'code' will be the HTTP response code from the server, e.g. 200
                                            // 'text' will be the raw response content
                                });
			} );
		}
	</script>

This will create a live camera view in the web_camera DIV, and when the Take Snapshot link is clicked it will take a still snapshot, convert it to a JPEG, and deliver a Data URI which is inserted into the cam_result DIV as a standard <img /> tag. Data URIs may be passed around like any URL, and can be submitted to your server as well (see below for example of this).

Step 4: Create a file upload.php and a folder uploads.

upload.php
<?php 

// be aware of file / directory permissions on your server 

move_uploaded_file($_FILES['webcam']['tmp_name'], 'uploads/webcam'.md5(time()).rand(383,1000).'.jpg'); 

?>
Done.Now, the full code goes here.
index.htmlupload.php

<!DOCTYPE html>
<html>
<head>
<title>Javascript Webcam Demo - <MyCodingTricks/></title>
</head>
<body>

<h3>Demonstrates simple 320x240 capture &amp; display</h3>


<div id="my_camera"></div>

	<!-- A button for taking snaps -->

<form>
		<input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
	</form>


<div id="results" class="well">Your captured image will appear here...</div>

	<!-- First, include the Webcam.js JavaScript Library -->
	<script type="text/javascript" src="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' );
		function take_snapshot() {
			// take snapshot and get image data
			Webcam.snap( function(data_uri) {
				// display results in page
				document.getElementById('results').innerHTML = 
					'
<h2>Here is your image:</h2>

' + 
					'<img src="'+data_uri+'"/>';
                                Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                            // Upload complete!
                                            // 'code' will be the HTTP response code from the server, e.g. 200
                                            // 'text' will be the raw response content
                                });
			} );
		}
	</script>
</body>
</html>
<?php // be aware of file / directory permissions on your server move_uploaded_file($_FILES['webcam']['tmp_name'], 'uploads/webcam'.md5(time()).rand(383,1000).'.jpg'); ?>
Wants some more features???Let’s do it.

Configuration

If you want to override the default settings,just call the Webcam.set() and pass in a hash with any of the following keys:

Param NameDefault ValueNotes
width(Auto)Width of the live camera viewer in pixels, defaults to the actual size of the DOM element.
height(Auto)Height of the live camera viewer in pixels, defaults to the actual size of the DOM element.
dest_width(Auto)Width of the captured camera image in pixels, defaults to the live viewer size.
dest_height(Auto)Height of the captured camera image in pixels, defaults to the live viewer size.
crop_width(Disabled)Width of the final cropped image in pixels, defaults to dest_width.
crop_height(Disabled)Height of the final cropped image in pixels, defaults to dest_height.
image_formatjpegDesired image format of captured image, may be “jpeg” or “png”.
jpeg_quality90For JPEG images, this is the desired quality, from 0 (worst) to 100 (best).
force_flashfalseSetting this to true will always run in Adobe Flash fallback mode.

Here is an example of overriding some parameters. Remember to call this before you attach the camera.

ExampleFull Code
Webcam.set({
width: 320,
height: 240,
dest_width: 640,
dest_height: 480,
image_format: 'jpeg',
jpeg_quality: 90,
force_flash: false
});

<div id="my_camera"></div>

<!-- A button for taking snaps -->

<form>
    <input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>

<script type="text/javascript" src="webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
        width: 320,
        height: 240,
        dest_width: 640,
        dest_height: 480,
        image_format: 'jpeg',
        jpeg_quality: 90,
        force_flash: false
});
    Webcam.attach( '#my_camera' );
    function take_snapshot() {
        // take snapshot and get image data
        Webcam.snap( function(data_uri) {
            // display results in page
            document.getElementById('results').innerHTML = 
                '
<h2>Here is your image:</h2>

' + 
                '<img src="'+data_uri+'"/>';
                            Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                        // Upload complete!
                                        // 'code' will be the HTTP response code from the server, e.g. 200
                                        // 'text' will be the raw response content
                            });
        } );
    }
</script>

Initialization

WebcamJS is initialized and activated by Attaching a live camera to a DOM element.DOM element must be already created. Pass in an ID or CSS selector to the Webcam.attach() function.

ExampleFull Code
Webcam.attach("#web_camera")

<div id="my_camera"></div>

<!-- A button for taking snaps -->

<form>
    <input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>

<script type="text/javascript" src="webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
        width: 320,
        height: 240,
        dest_width: 640,
        dest_height: 480,
        image_format: 'jpeg',
        jpeg_quality: 90,
        force_flash: false
});
    Webcam.attach( '#my_camera' );
    function take_snapshot() {
        // take snapshot and get image data
        Webcam.snap( function(data_uri) {
            // display results in page
            document.getElementById('results').innerHTML = 
                '
<h2>Here is your image:</h2>

' + 
                '<img src="'+data_uri+'"/>';
                            Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                        // Upload complete!
                                        // 'code' will be the HTTP response code from the server, e.g. 200
                                        // 'text' will be the raw response content
                            });
        } );
    }
</script>

Cropping The Image

WebcamJS can also crop the final image for you, to any dimensions you like. This is useful for when you want a square image (perhaps for a website profile pic), but you want to capture the image from the user’s webcam at 4:3 ratio to be fully compatible (some cameras require 4:3 and cannot capture square images). To do this, include crop_width and crop_height params, specifying the area to crop out of the center of the final image:

ExampleFull Code
Webcam.set({
width: 320,
height: 240,
crop_width: 240,
crop_height: 240,
image_format: 'jpeg',
jpeg_quality: 90,
force_flash: false
})
<div id="my_camera"></div>

<!-- A button for taking snaps -->

<form>
    <input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>

<script type="text/javascript" src="webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
        width: 320,
        height: 240,
        crop_width: 240,
        crop_height: 240,
        image_format: 'jpeg',
        jpeg_quality: 90,
});
    Webcam.attach( '#my_camera' );
    function take_snapshot() {
        // take snapshot and get image data
        Webcam.snap( function(data_uri) {
            // display results in page
            document.getElementById('results').innerHTML = 
                '
<h2>Here is your image:</h2>

' + 
                '<img src="'+data_uri+'"/>';
                            Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                        // Upload complete!
                                        // 'code' will be the HTTP response code from the server, e.g. 200
                                        // 'text' will be the raw response content
                            });
        } );
    }
</script>
This would crop a 240×240 square out of the center of the 320×240 webcam image.

Freezing/Previewing the Image

Want to provide your users with the ability to “freeze” (i.e. preview) the image before actually saving a snapshot? Just call Webcam.freeze() to freeze the current camera image. Then call Webcam.snap() to save the frozen image, or call Webcam.unfreeze() to cancel and resume the live camera feed. The idea here is to provide a photo-booth-like experience, where the user can take a snapshot, then choose to keep or discard it, before actually calling Webcam.snap() to save the image. View Demo

Flipping The Image (Mirror Mode)

If you want, WebcamJS can “flip” i.e mirror, both the live preview and captured image horizontally. This will produce a flipped image, as if you were looking in a mirror. To enable this optional feature, include the flip_horiz param, and set it to true.

ExampleFull Code
Webcam.set({
width: 320,
height: 240,
flip_horiz: true
})
<div id="my_camera"></div>

<!-- A button for taking snaps -->

<form>
    <input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>

<script type="text/javascript" src="webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
        width: 320,
        height: 240,
        flip_horiz: true
});
    Webcam.attach( '#my_camera' );
    function take_snapshot() {
        // take snapshot and get image data
        Webcam.snap( function(data_uri) {
            // display results in page
            document.getElementById('results').innerHTML = 
                '
<h2>Here is your image:</h2>

' + 
                '<img src="'+data_uri+'"/>';
                            Webcam.upload( data_uri, 'upload.php', function(code, text) {
                                        // Upload complete!
                                        // 'code' will be the HTTP response code from the server, e.g. 200
                                        // 'text' will be the raw response content
                            });
        } );
    }
</script>

Resources

Pixlcore webcamjs I would like to hear your Feedback,so do not forget to send me your feedback using Comment. If you like this article then please share it with others.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

55 Responses

  1. Shubham thanks for this code. It’s very helpful. I read the responses above but need more clarification on how to take an input text field with the file name and pass it to the PHP upload.php method? Thanks for your help!

  2. ultrasamad says:

    Thanks very much! It really helps.

  3. ashish asrani says:

    Hi I have signed up but still can’t download webcam js.

  4. Hi I have signed up but still can’t download webcam js.

  5. Tim Casey says:

    What I want to do, this script manages for the most part. Overall, what I would like to do is this.

    I have a product coming off of my assembly line. I want to install POE IP cameras. I am concerned about dragging down the network by feeding a live stream to it, so, I would rather “Free stream?” for lack of a better way to say that, over the internet and use a manual trigger to capture still images of a given finished product, with a time and date stamp, which I can move to a database on our company network to store for later reference if a customer says they have a defect.

    I would like to modify this script I see here to allow for the cameras (4) to stream freely and use my network only to capture stills off of each of the 4 finish stations, with a dedicated camera at each, tied back to a 4 port switch and back to the main factory switch from there, download them, time and date stamp them, when an operator presses the manual trigger button, and store them to a database, then clear the image so the capture frame is ready for the next one and return take the focus back to the live stream to avoid bogging our network down.

    Any advice you might have would go a long way.

    Thank you

  6. Orte Keri says:

    Hello,

    Is there a way to add two extra HTML INPUT and have the filename be named by the users input. For example if you enter Shubham (first html input) Kumar (second html input) the filename would be shubham_kumar.jpg. This would happen after the button is clicked.

    Thank you very much for your help!

  7. otero says:

    how can I add a html TEXT (which a user can enter) and use that as a file name when picture gets saved?
    I guess information has to be somehow transferred into upload.php?
    Webcam.upload( data_uri, ‘upload.php’, function(code, text)

    Thank you

  8. ken says:

    please help me i have been trying to download this script its not working

    • What’s the Exact Problem you’re facing?

      1. Unable to Download the Script
      2. Script is not working after downloading

      Thanks
      Shubham

      • Aniket Luharia says:

        Hi Shubham,

        Not able to download anything even after giving correct email id.
        And also not getting any confirmation mail….
        Please Help…!

        Thanks,
        Aniket

  9. Ravikant says:

    Hi Sir,
    I am working on Integrating the Face Detection in .Net website. I have used you js and able to capture the Image , but don’t know how to store it on the server in particular folder?
    Please Guide me

    • Hi Ravikant,

      I don’t know anything about .NET Programming.

      If you want any help in PHP/jQuery or anything related to my blog topic, then I can surely help you.

      Best Regards,
      Shubham

  10. Swati says:

    Hi,

    I was using the webcam.js script for capturing the image. I am getting nice image with resolution 2560 x 1440 pixels.
    With webcam.js I can capture images from single camera.
    But I have requirement to capture the images from multiple webcams.
    So is there any feature or anything so that I can detect all the camera attached to my system and able to capture images from all camera through webcam.js or can you give me some solution on that?

    Please do the needfull.

  11. arpit says:

    hi,

    Can i get list of cameras if more than 1 camera is attached and also with that on changing of camera name that camera image need to come on screen.

  12. Ante988 says:

    Hi,

    I get error : Webcam is not loaded yet.

    Please help.
    Thanks.

  13. Jose A says:

    Thanks, Works fine!

  14. Dinky Malubag says:

    Dear Sir,

    I am using your codes, but in Webcam.upload, I am using JSP instead of php. I am new in this development tool. I am hoping you could provide a code for JSP, it would help solve my problem. Thank you.

  15. Imran Khan says:

    Dear Sir,

    Your script not working on google chrome. Kindly see attached screenshot.

    Regards,

    Imran Khan

    • Hi Imran,

      Due to security reasons, http sites are not allowed to access webcam in Google Chrome. Only HTTPS sites are allowed. So you need to have https site.

      Best Regards,
      Shubham

  16. Imran Khan says:

    Dear Sir,

    locally your script working perfectly on all browser but when i live the script and use google chrome so it’s show attached picture error. Kindly help sir.

    Regards,

    Imran Khan

  17. sukhesh says:

    hi sir, for me images are not storing into uploads folder..

  18. Josh says:

    Thanks for the script. Please i want to add different names to each pics when taking the snap shots, how can i go about it

  19. Afshan Shujat says:

    It’s good help me, Can you tell me how can i remove/close webcam once it’s done?

  20. MIhir Dave says:

    Thanks For the code it’s working fine…But i want to get cropped image in another dimension not in 240X240 (E.g. 150X150) So Let me know how to do it….

  21. SK Pradhan says:

    when i open your index page it is redirected to http://demo.mycodingtricks.com/

  22. Hi,

    I have used your code and successfully captured n stored in folder.But i want to store webcam captured image in specified folder and captured image path in mysql database using php.
    So please help me
    Thanks.

    • Hey Dnyaneshwar,

      Replace:

      move_uploaded_file($_FILES['webcam']['tmp_name'], 'uploads/webcam'.md5(time()).rand(383,1000).'.jpg');

      To:

      $connection = mysqli_connect('localhost','username','password','database');
      
      $tmp_name = $_FILES['webcam']['tmp_name'];
      $name = $_FILES['webcam']['name'];
      $target = 'uploads/webcam'.md5(time()).rand(383,1000).'.png';
      $upload = move_uploaded_files($tmp_name,$target);
      if($upload){
        $insert = mysqli_query($connection,"INSERT into `gallery` (`name`,`target`)  VALUES ('$name','$target')");
      }
      

      and Create a table gallery in your MySQL database:

      CREATE TABLE gallery
      (
          id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
          name VARCHAR(110) NOT NULL,
          target VARCHAR(200) NOT NULL
      );
      

      Read this article to connect with MySQLi

      I hope that it helps you.

      Cheers,
      Shubham

    • Dinky says:

      Sir, I have the same case, but I i want to store webcam captured image in specified folder and captured image path in mysql database using jsp

      • Hi Dinky,

        I don’t know about jsp but I can tell you the way to do it.

        First of all save the random file name in a variable.

        $randName = md5(time()).rand(383,1000).”.jpg”;

        And then use this random name to generate to different paths for upload folder and database file.

        $upload_file = “/uploads/”.$randName;

        $url_for_database = ” http://your website.com/uploads/”.$randName;

        Hope it will help.

        If you didn’t get something do let me know.

        Best Regards,
        Shubham

  23. Aledare Yomi says:

    Drop Box says that the link has expired. Please help. Thanks.

  24. I used your code after looking at the previous code by David Walsch using HTML5 to access camera. I thought that yours may have fixed the iphone problem but it does not. Still, thank you for your code. Especially the part about cropping and the other features, very handy.

  1. February 17, 2016

    […] Read More Demo Download […]

Leave a Reply

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