Wednesday, March 5, 2014
PHP Webcam Image Capture
The following script is to capture the image from webcam and save that image.
index.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div id="camera">
<video autoplay id="vid" style="display:;" width="240">
</video>
<canvas id="canvas" height="380" style="border:1px solid #d3d3d3;"></canvas><br>
<button onclick="snapshot()">Take Picture</button>
<input type="button" value="Save" id="savepic" />
</div>
<div id="mypic" width="240"></div>
</body>
<script type="text/javascript">
var pid="<?php echo uniqid();?>";
var video = document.querySelector("#vid");
var canvas = document.querySelector('#canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
var onCameraFail = function (e) {
console.log('Camera did not work.', e);
};
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia({video:true}, function (stream) {
video.src = window.URL.createObjectURL(stream);
localMediaStream = stream;
}, onCameraFail);
function snapshot() {
var video =document.getElementById("vid");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var localMediaStream = null;
ctx.drawImage(video, -60, -40);
}
document.getElementById("savepic").onclick=function(){
var canvas1 = document.getElementById("canvas");
if (canvas1.getContext) {
var ctx = canvas1.getContext("2d");
var myImage = canvas1.toDataURL("image/png").replace("image/png", "image/octet-stream");
}
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest;
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("mypic").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","upload_photo.php",true);
xmlhttp.setRequestHeader('Content-Type', 'canvas/upload');
xmlhttp.send("canvasData="+myImage+"&pid="+pid);
document.getElementById('camera').style.display="none";
alert("Photo saved");
}
</script>
</html>
upload_photo.php
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
$image=$GLOBALS['HTTP_RAW_POST_DATA'];
$filter=substr($image, strpos($image, ",")+1,strlen($image)-60);
$pidpos = strpos($image, "pid=");
$pid = substr($image,$pidpos+4);
$dir = "photo/";
if(!is_dir($dir)){
mkdir($dir);
}
$decode=base64_decode($filter);
$fp = fopen( 'photo/'.$pid.'.png', 'wb' );
fwrite( $fp, $decode);
fclose( $fp );
echo '<img src="'.$dir.$pid.'.png" />';
}
else{
echo "No image found";
}
?>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment