html5調用攝像頭並拍照


隨着flash被禁用,flash上傳附件的方式已成為過去,現在開始用html5上傳了.本片文章就是介紹如何使用html5拍照,其實挺簡單的原理:

調用攝像頭采集視頻流,利用canvas的特性生成base64圖片,

其完整代碼如下,需要使用https訪問才不會有調用攝像頭安全問題,另外IE內核是無法使用的.這個可以作為一個單獨頁面來被父頁面調用

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>html5拍照</title>
<style type="text/css">
body{overflow-y:auto;overflow-x:auto;margin:0;}
#cameraBtn,#cameraDiv{padding:5px;}
.big-btn-blue{ display:inline-block; min-width:80px; height:30px; margin:0 5px; padding:0 15px; vertical-align:top; line-height:30px; text-align:center; font-size:14px; font-family: "微軟雅黑";
 color:#fff; border-radius:2px; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; cursor:pointer; }
.big-btn-blue{ -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; transition: all 0.3s ease;}/*動畫*/
.big-btn-blue{ border:1px solid #3194dd; background-color:#3194dd;}/*純藍色*/
</style>
<script type="text/javascript">
//訪問用戶媒體設備的兼容方法
function getUserMedia(constrains,success,error){
    if(navigator.mediaDevices.getUserMedia){
        //最新標准API
        navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
    } else if (navigator.webkitGetUserMedia){
        //webkit內核瀏覽器
        navigator.webkitGetUserMedia(constrains).then(success).catch(error);
    } else if (navigator.mozGetUserMedia){
        //Firefox瀏覽器
        navagator.mozGetUserMedia(constrains).then(success).catch(error);
    } else if (navigator.getUserMedia){
        //舊版API
        navigator.getUserMedia(constrains).then(success).catch(error);
    }else{
        alert("不支持的瀏覽器");
    }
}
//成功的回調函數
function success(stream){
    //兼容webkit內核瀏覽器
    var CompatibleURL = window.URL || window.webkitURL;
    //將視頻流設置為video元素的源
    try {
        video.srcObject = stream;
    } catch (e) {
        video.src = CompatibleURL.createObjectURL(stream);
    }
    //播放視頻
    video.play();
}
//異常的回調函數
function error(error){
   alert("訪問用戶媒體設備失敗,"+error.name+""+error.message);
}

/**
 * 獲取當前靜態頁面的參數
 * 返回值和使用方法類似java request的getparamater
 * 不同: 當取得的為數組(length>1)時調用toString()返回(逗號分隔每個元素)
 * @param {Object} name
 * @return {TypeName} 
 */
function getPara(name,search){
    var p = getParas(name,search);
    if(p.length==0){
        return null;
    }else if(p.length==1){
        return p[0];
    }else{
        return p.toString();
    }
}

/**獲取當前靜態頁面的參數
 * 返回值和使用方法類似java request的getparamaterValues
 * @param {Object} name 要取出的參數名,可以在參數字符串中重復出現
 * @param {Object} search 手工指定要解析的參數字符串,默認為當前頁面后跟的參數
 * @return {TypeName} 
 */
function getParas(name,search){
    if(!search){
        search = window.location.search.substr(1);//1.html?a=1&b=2
    }
    var para = [];
    var pairs = search.split("&");//a=1&b=2&b=2&c=2&b=2
    for(var i=0;i<pairs.length;i=i+1){
        var sign = pairs[i].indexOf("="); 
        if(sign == -1){//如果沒有找到=號,那么就跳過,跳到下一個字符串(下一個循環)。    
            continue; 
        }
        var aKey = pairs[i].substring(0,sign);
        if(aKey==name){
            para.push(unescape(pairs[i].substring(sign+1)));
        }
    }
    return para;
}
//開啟攝像頭
function captureInit(){
    if ((navigator.mediaDevices!=undefined && navigator.mediaDevices.getUserMedia!=undefined) 
            || navigator.getUserMedia!=undefined
            || navigator.webkitGetUserMedia!=undefined
            || navigator.mozGetUserMedia!=undefined){
        document.getElementById("help").style.display="none";
        //調用用戶媒體設備,訪問攝像頭,改為觸發事件
        getUserMedia({video:{width:imgWidth,height:imgHeight}},success,error);
        if(captureState==0){
            captureState=1;//標記此按鈕已點擊
        }
    } else {
        captureState=0;//異常標識按鈕沒點
        alert("你的瀏覽器不支持訪問用戶媒體設備或訪問地址不是https開頭,您可以點擊右側下載解決方案");
        document.getElementById("help").style.display="inline-block";
    }
}
//注冊拍照按鈕的單擊事件
function capture(){
    //繪制畫面
    if(captureState==0){
        alert("請先開啟攝像頭");
        return;
    }
    context.drawImage(video,0,0,imgWidth,imgHeight);//后面兩個長寬
    //canvas.toDataURL("image/png");//即可得到base64編碼
    captureState=2;
}
//確認按鈕返回給父頁面的函數
function queren(){
    if(captureState!=2){
        alert("請先開啟攝像頭並拍照");
        return;
    }
    var base64=canvas.toDataURL("image/jpeg");
    var pics={};
    pics.filetypeid=filetypeid;//返回給前端
    pics.base64=base64;
    if(window.opener){
        window.opener[cb](pics);// /FileUploadTmp/為項目臨時文件夾相對路徑
        window.close();
    }else if(window.parent){
        window.parent[cb](pics);
        window.parent.$("#dialog_ifr_html").dialog("close");//close會導致flash未執行完就銷毀,頁面JS報錯
    }else{
        window.close();
    }
}
</script>
</head>

<body>
<div id="cameraBtn">
    <input type="button" id="init" onclick="captureInit()" value="開啟攝像頭"/>
    <input type="button" id="capture" onclick="capture()" value="拍照"/>
    <input type="button" id="queren" onclick="queren()" value="確定"/>
    <span id="help" style="display:none;"><a href="/static/ad/down/camera.doc">點此下載無法拍照的解決方案</a></span>
</div>
<div id="cameraDiv">
    <!-- 視頻流 -->
      <video id="video" autoplay style="width: 300px;height: 200px"></video>
     <!--描繪video截圖-->
    <canvas id="canvas" width="300" height="200"></canvas>
</div>
<script type="text/javascript">
var cb=getPara("cb")||"setImg";
var filetypeid=getPara("filetypeid")||"filetypeid";//附件類型id
var video=document.getElementById("video");
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var imgWidth=getPara("width")||"300";//這個值div的寬一致
var imgHeight=getPara("height")||"200";//這個值div的高一致
var captureState=0;//未開啟,1已開啟,2已拍照,為2才可點擊確認按鈕
var style = getPara("style")||"big-btn-blue";
video.style.width=imgWidth;
video.style.height=imgHeight;
var st = style.split(",");
document.getElementById("init").className=st[0];
document.getElementById("capture").className=st[1]||st[0];
document.getElementById("queren").className=st[2]||st[0];
document.getElementById("help").className=st[3]||st[0];
</script>
</body>
</html>

相信略懂js和html5的人都能看懂代碼,非常的簡單.而且都不需要用到jquery.

另外備注下:IE內核瀏覽器是無法實現的.因為不支持getUserMedia方法.

注:文章內容來自於本人在CSDN上發布的文章


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM