奥非域

WebPascal脚本模型教程 - 网页调用摄像头进行拍照与上传

如何通过网页调用摄像头进行拍照,并将照片上传到服务器上呢?其实非常简单,因为支持html5的浏览器已经帮我们实现了硬件的支持,我们直接看代码吧:

web前端代码:

<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

<video  id="video" autoplay style="width: 480px;height: 320px"></video>
<div>
    <button id="capture">Camera</button> <button id="upimg">Upload</button>
</div>
<canvas id="canvas" width="480" height="320"></canvas>

<script>  
    var video = document.getElementById('video');
    var canvas = document.getElementById('canvas');
    var capture = document.getElementById('capture');
    var upimg = document.getElementById('upimg');
    var context = canvas.getContext('2d');
    function getUserMediaToPhoto(constraints,success,error) {
        if(navigator.mediaDevices.getUserMedia){
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        }else if (navigator.webkitGetUserMedia) {
            //webkit
            navigator.webkitGetUserMedia(constraints,success,error);
        }else if(navigator.mozGetUserMedia){
            //firefox
            navigator.mozGetUserMedia(constraints,success,error);
        }else if(navigator.getUserMedia){
            //old API
            navigator.getUserMedia(constraints,success,error);
        }
    }
    function success(stream){
        // srcObject
        if ("srcObject" in video) {
            video.srcObject = stream;
        } else {
            video.src = window.URL.createObjectURL(stream);
        }
        video.onloadedmetadata = function (e) {
            video.play();
            videoPlaying = true;
        };
    }
    function error(error) {
        console.log('Access to user media failed : ',error.name,error.message);
    }
    if(navigator.mediaDevices.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia || navigator.getUserMedia){
        getUserMediaToPhoto({video:{width:480,height:320}},success,error);
    }else{
        alert('Your browser does not support access to user media devices');
    }
    capture.addEventListener('click',function() {
        // video to canvas
        context.drawImage(video,0,0,480,320);
    })
    upimg.addEventListener('click',function() {
        var imgData=document.getElementById("canvas").toDataURL("image/png");
        var data=imgData.substr(22);
        //debugger;
        console.log(data);
        $.post('upimg.api',{'img':data});
    })
 </script>

webpascal脚本代码:

<?
//log(input.img,'xxx');
$f:=Base64toFile(urlencode(input.img,65001,false),
    formatdatetime('yyyyMMddhhmmsszzz".png"',now));
if $f<>'' then begin
'success,file:'$f;' <img src="'$f'">'
end else begin
'error.';
end;
?>

效果图: