我正在尝试从网络摄像头随机捕获图像,然后将其保存到我的服务器上,现在我正在使用getUserMedia将网络摄像头传输到视频元素,然后我可以使用按钮将图像捕捉到画布,但我不知道如何将该图像从画布保存到我的服务器.
另一个问题是getUserMedia只适用于Chrome,Opera和Firefox,是否有任何替代的IE?
这是我目前正在使用的:
<video id="video" width="640" height="480" autoplay></video> <button id="snap">Snap Photo</button> <canvas id="canvas" width="640" height="480"></canvas> <button id="getBase" onclick="getBase()">Get Base64</button> <textarea id="textArea"></textarea> <script> // Put event listeners into place window.addEventListener("DOMContentLoaded",function() { // Grab elements,create settings,etc. var canvas = document.getElementById("canvas"),context = canvas.getContext("2d"),video = document.getElementById("video"),videoObj = { "video": true },errBack = function(error) { console.log("Video capture error: ",error.code); }; // Put video listeners into place if(navigator.getUserMedia) { // Standard navigator.getUserMedia(videoObj,function(stream) { video.src = stream; video.play(); },errBack); } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed navigator.webkitGetUserMedia(videoObj,function(stream){ video.src = window.webkitURL.createObjectURL(stream); video.play(); },errBack); } // Trigger photo take document.getElementById("snap").addEventListener("click",function() { context.drawImage(video,640,480); }); document.getElementByID("getBase").addEventListener("click",getBase()); },false); function getBase(){ var imgBase = canvas.toDataURL("image/png"); document.getElementByID("textArea").value=imgBase; } </script>`
谢谢堆
解决方法
您可以使用canvas.toDataUrl获取一个base64编码的字符串,您可以将其作为参数发布到服务器上的脚本,该脚本将读取并存储为图像文件.
以下是这种方法的实际实现的缩写版本:
<script> function saveImage(){ var xmlhttp; xmlhttp=((window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP")); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4){ if(xmlhttp.status==200){ //handle success } } } xmlhttp.open("POST",baseURL,true); var oldCanvas = under.toDataURL("image/png"); var params=oldCanvas; xmlhttp.setRequestHeader("Content-type","application/upload"); xmlhttp.setRequestHeader("Content-length",params.length); xmlhttp.setRequestHeader("Connection","close"); xmlhttp.send(params); } </script>
这里是一个示例PHP脚本,接受base64字符串,转换为.png,给它一个随机的文件名,并保存:
<?PHP if((isset($GLOBALS["HTTP_RAW_POST_DATA"]))){ //some validation is necessary,this is just a proof of concept if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){ $params=explode('&',$GLOBALS["HTTP_RAW_POST_DATA"]); $imgsrc=str_replace(' ','+',$params[0]); $im = imagecreatefrompng($imgsrc); } if($im){ $background = imagecolorallocatealpha($im,255,127); imagecolortransparent($im,$background); //random file name $m = rand(10e16,10e24); $filename=base_convert($m,10,36); //save image imagepng($im,'images/'.$filename.'.png'); imagedestroy($im); $size = getimagesize('images/'.$filename.'.png'); $iH=$size[1]; $iW=$size[0]; echo "{\"filename\":\"".$filename."\",\"width\":\"".$iW."\",\"height\":\"".$iH."\"}"; } } ?>