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>