Take Photo Using Web Camera in PHP


Recently I have implemented take photo using web camera in my website for the profile photo. I found jQuery webcam plugin for the same. With this plugin image can be display to canvas to store the image on the server. So in this tutorial I am giving simple steps to implement take photo using web camera in PHP with live demo.

First we need to add following scripts in head tag.

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

You can download jQuery-webcam from github.

Now to display the webcam area just add following HTML line:

 <div id="webcam"></div> 

Following lines if no camera detected:

<div id="nocamera">
	<div class="message">
		Video has not detected any available cameras on your system. Please connect a camera and try again.
	</div>
</div>

With preview image our full html code will be like below:

<div id="cambox" >
	<div id="webcam"></div>
	<div id="tiktik">
		<span class="timer">3</span>
		<span class="click"><img alt="take photo" src="img/camera_icon.png" onclick="capturePic()" /></span>
	</div>
	<div id="nocamera">
		<div class="message">
			Video has not detected any available cameras on your system. Please connect a camera and try again.
		</div>
	</div>
	<div id="preview">
		<img id="previewImg" alt="preview Image" height="240" width="320" src="img/preload.gif" />
		<span class="close"></span>
	</div>
</div>

Now we need to add following style css in head of the page to better look of the camera:

#cambox{
		position:relative;
		width:450px;
		height: 320px;
		margin: 0 auto;
	}

	#webcam, #preview, #nocamera {
		position:absolute;
		margin:10px 20px;
		margin-left:60px;
		width: 320px;
		height: 240px;
		border:5px solid #999;
		background:#eee;
		-webkit-border-radius: 5px;
		-moz-border-radius: 5px;
		border-radius: 5px;
	}

	#webcam {
		z-index:2000;
	}

	#preview {
		display:none;
		z-index:5000;
	}

	#nocamera {
		display:none;
		z-index:9900;
	}

	#buttons{
		position:absolute;
		bottom:0;
		right:165px;
		z-index:100;
	}

	#flash {
		position:absolute;
		top:0px;
		left:0px;
		z-index:5000;
		width:100%;
		height:500px;
		background-color:#c00;
		display:none;
	}

	object {
		display:block;
		position:relative;
		z-index:1000;
	}

	#tiktik{
		position:absolute;
		margin-left:67px;
		height:40px;
		z-index:2100;
		top:220px;cursor:pointer;
		background:transparent;
	}

	.message{
		padding:80px 10px;
	}

	.timer{
		font-size:26px;
		font-weight:bold;
		color:#fff;
		padding-left:153px;
		display:none;
	}

	.click{
		padding-left:135px;
	}

	.close{
		position: absolute;
		right: 0;
		color:#fff;
		top: 0;
		cursor:pointer;width:22px;height:22px;display:block;background:url(img/close_video_icon.png) top;
	}
	.close:hover{
		position: absolute;
		right: 0;
		color:#fff;
		top: 0;
		cursor:pointer;width:22px;height:22px;display:block;background:url(img/close_video_icon.png) bottom;
	}

Now we need following script to set the camera and capture the picture:

$("#preview .close").click(function(){
	$("#buttons .save_profile_pic").attr('disabled',true);
	$('.timer').hide();
	$('#preview').hide();
	$('#previewImg').attr('src',baseurl+'img/preload.gif');
	$('.click').show();
});

var profileImage = null;
$("#buttons .save_profile_pic").click(function(){

	$.post(baseurl+"save_image_from_webcam.php",
	{ image: profileImage},
	function(data){
		window.location = 'save_image_from_webcam.php';
	});
});

function capturePic(){
	$('.click').hide();
	$('.timer').show();
	webcam.capture(3);
}

function webcam_init() {
	var pos = 0, ctx = null, saveCB, image = [];
	var canvas = document.createElement("canvas");
	canvas.setAttribute('width', 320);
	canvas.setAttribute('height', 240);

		if (canvas.toDataURL) {
			ctx = canvas.getContext("2d");

			image = ctx.getImageData(0, 0, 320, 240);

			saveCB = function(data) {

				var col = data.split(";");
				var img = image;

				for(var i = 0; i < 320; i++) {
					var tmp = parseInt(col[i]);
					img.data[pos + 0] = (tmp >> 16) & 0xff;
					img.data[pos + 1] = (tmp >> 8) & 0xff;
					img.data[pos + 2] = tmp & 0xff;
					img.data[pos + 3] = 0xff;
					pos+= 4;
				}

				if (pos >= 4 * 320 * 240) {
					ctx.putImageData(img, 0, 0);
					$('#preview').show();
					$.post(baseurl+"save_image_from_webcam.php", {type: "data", image: canvas.toDataURL("image/png")},function(data){
						$("#buttons .save_profile_pic").attr('disabled',false);
						profileImage = data;
						$('#previewImg').attr('src',''+baseurl+data);
					});
					pos = 0;
				}
			};
		}else{

			saveCB = function(data) {
				image.push(data);

				pos+= 4 * 320;

				if (pos >= 4 * 320 * 240) {
						$('#preview').show();
						$.post(baseurl+"save_image_from_webcam.php", {type: "pixel", image: image.join('|')},function(data){
							$("#buttons .save_profile_pic").attr('disabled',false);
							profileImage = data;
							$('#previewImg').attr('src',''+baseurl+data);
						});
						pos = 0;
						image = [];
				}
			}
		}

		$("#webcam").webcam({
				width: 320,
				height: 240,
				mode: "callback",
				swffile: baseurl+"js/webcam/jscam_canvas_only.swf",

				onSave: saveCB,

				onCapture: function () {

					jQuery("#flash").css("display", "block");
					jQuery("#flash").fadeOut("fast", function () {
						jQuery("#flash").css("opacity", 1);
					});

					webcam.save();
				},

				onTick: function(remain) {
					$('.timer').show();

					if (0 == remain) {
						$('.timer').hide();
					} else {
						jQuery(".timer").text(remain);
					}
				},

				debug: function (type, string) {
						if(type == 'error'){
							$("#nocamera").show();
						}else{
							$("#nocamera").hide();
						}

				},

				onLoad: function() {
					//var cams = webcam.getCameraList();
				}
		});

}

(function ($) {
	webcam_init();
})(jQuery);

Now the camera has been set to 320*240 size and when you click on camera icon, the timer will show for 3 second and after flash the image will be taken and preview will be display over the camera.

Take Photo Using Web Camera in PHP
Take Photo Using Web Camera in PHP

Now depending on the browser, there are two ways to get the image. From the canvas we can get the raw data of image to save directly into an image like below:

$srcImg = imagecreatefrompng($_POST['image']);

In second way you can get the image in pixels, So to save this you need to use following script in save_image_from_webcam.php file:

$uploadWidth = 320; $uploadHeight = 240;
$srcImg = imagecreatetruecolor($uploadWidth, $uploadHeight);
foreach (explode("|", $_POST['image']) as $y =&gt; $cs) {
	foreach (explode(";", $cs) as $x =&gt; $color) {
		imagesetpixel($srcImg, $x, $y, $color);
	}
}

$filename = 'sample_img.png';
$destination = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$filename;
$dstImg = @imagecreatetruecolor($uploadWidth, $uploadHeight);
imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $uploadWidth, $uploadHeight, $uploadWidth, $uploadHeight);
$write = imagepng($dstImg, $destination, 9);

imagedestroy($dstImg);

So this way you can take photo using wen camera in PHP.

Live Demo

  • Bas

    Is the complete source of this tutorial available for download?

    • sweet salony

      http://live24u.com/

      Live24u is the most popular Programming & Web Development blog. Our mission is to provide the best online resources on programming and web development. We deliver the useful and best tutorials for web professionals — developers, programmers, freelancers and site owners. Any visitors of this site are free to browse our tutorials, live demos and download scripts.