HTML5ææ¯æ¯æWebAppå¨ææºä¸æç
§ï¼æ¾ç¤ºå¨é¡µé¢ä¸å¹¶ä¸ä¼ å°æå¡å¨ãè¿æ¯ææºå¾®ååºç¨ä¸å¸¸è§çåè½ï¼å½ç¶ä½ ä¹å¯ä»¥å¨å
¶å®ç±»ååºç¨ä¸éå½ä½¿ç¨æ¤ææ¯ã
ãã1ã è§é¢æµ
ã
ãHTML5 ç The Media Captureï¼åªä½ææï¼ API æä¾äºå¯¹æå头çå¯ç¼ç¨è®¿é®ï¼ç¨æ·å¯ä»¥ç´æ¥ç¨
getUserMediaï¼è¯·æ³¨æç®åä»
ChromeåOperaæ¯æï¼è·å¾æå头æä¾çè§é¢æµãæ们éè¦åçæ¯æ·»å ä¸ä¸ªHTML5 ç Video
æ ç¾ï¼å¹¶å°ä»æå头è·å¾çè§é¢ä½ä¸ºè¿ä¸ªæ ç¾çè¾å
¥æ¥æºã
<video id=âvideoâ autoplay=â"></video>
<script>
var video_element=document.getElementById(âvideoâ);
if(navigator.getUserMedia){ // operaåºä½¿ç¨opera.getUserMedianow
navigator.getUserMedia(âvideoâ,success,error); //successæ¯åè°å½æ°,å½ç¶ä½ ä¹å¯ä»¥ç´æ¥å¨æ¤åä¸ä¸ªå¿åå½æ°
}
function success(stream){
video_element.src=stream;
}
</script>
æ¤æ¶ï¼video æ ç¾å
å°æ¾ç¤ºå¨æçæåè§é¢æµãä¸é¢éè¦è¿è¡æç
§äºã
ãã2ã æç
§
ããæç
§æ¯éç¨HTML5çCanvasåè½ï¼å®æ¶æè·Videoæ ç¾çå
容ï¼å 为Videoå
ç´ å¯ä»¥ä½ä¸ºCanvaså¾åçè¾å
¥ï¼æ以è¿ä¸ç¹å¾å¥½å®ç°ã主è¦ä»£ç å¦ä¸ï¼
var canvas=document.createElement(âcanvasâ); //å¨æå建ç»å¸å¯¹è±¡
var ctx=canvas.getContext(â2dâ);
var cw=vw,ch=vh;
ctx.fillStyle=â#ffffffâ;
ctx.fillRect(0,0,cw,ch);
ctx.drawImage(video_element,0,0,cw,ch,0,0,vw,vh); //å°video对象å
æå®çåºåææç»å¶å°ç»å¸ä¸æå®çåºåï¼å¯è¿è¡ä¸ç大ä¸çä½çç»å¶ã
document.body.append(canvas);
ãã3ã å¾çè·å
ããä»Canvasè·åå¾çæ°æ®çæ ¸å¿æè·¯æ¯ç¨canvasçtoDataURLå°Canvasçæ°æ®è½¬æ¢ä¸ºbase64ä½ç¼ç çPNGå¾åï¼ç±»ä¼¼äºâdata:image/png;base64,xxxxxâçæ ¼å¼ã
var imgData=canvas.toDataURL(âimage/pngâ);
è¿æ ·ï¼imgDataåéå°±åå¨äºä¸é¿ä¸²çå符æ°æ®å
容ï¼è¡¨ç¤ºçå°±æ¯ä¸ä¸ªPNGå¾åçbase64ç¼ç ãå 为çæ£çå¾åæ°æ®æ¯base64ç¼ç éå·ä¹åçé¨åï¼æ以è¦è®©å®é
æå¡å¨æ¥æ¶çå¾åæ°æ®åºè¯¥æ¯è¿é¨åï¼æ们å¯ä»¥ç¨ä¸¤ç§åæ³æ¥è·åã
ãã第ä¸ç§ï¼æ¯å¨å端æªå22ä½ä»¥åçå符串ä½ä¸ºå¾åæ°æ®ï¼ä¾å¦ï¼
var data=imgData.substr(22);
ããå¦æè¦å¨ä¸ä¼ åè·åå¾çç大å°ï¼å¯ä»¥ä½¿ç¨ï¼
var length=atob(data).length; //atob å¯è§£ç ç¨base-64解ç çå串
ãã第äºç§ï¼æ¯å¨å端è·åä¼ è¾çæ°æ®åç¨åå°è¯è¨æªå22ä½ä»¥åçå符串ï¼ä¹å°±æ¯å¨åå°ç¥è¿ä¸é¢è¿æ¥ç´æ¥ä¸ä¼ ï¼ãä¾å¦PHPéï¼
$image=base64_decode(str_replace(âdata:image/jpeg;base64,â,â,$data);
ãã4ã å¾çä¸ä¼
ããå¨å端å¯ä»¥ä½¿ç¨Ajaxå°ä¸é¢è·å¾çå¾çæ°æ®ä¸ä¼ å°åå°èæ¬ãä¾å¦ä½¿ç¨jQueryæ¶å¯ä»¥ç¨ï¼
$.post(âupload.phpâ,{âdataâ:data});
å¨åå°æ们ç¨PHPèæ¬æ¥æ¶æ°æ®å¹¶åå¨ä¸ºå¾çã
function convert_data($data){
$image=base64_decode(str_replace(âdata:image/jpeg;base64,â,â,$data);
save_to_file($image);
}
function save_to_file($image){
$fp=fopen($filename,âw');
fwrite($fp,$image);
fclose($fp);
}
ãã以ä¸ç解å³æ¹æ¡ä¸ä»
è½ç¨äºWeb Appæç
§ä¸ä¼ ï¼ä¹å¯ä»¥éè¿Canvasçç¼è¾åè½å½æ°æä¾å¾çç¼è¾ï¼ä¾å¦è£åªãä¸è²ãæ¶é¸¦ãåç¹çåè½ï¼ç¶åæç¨æ·ç¼è¾å®çå¾çä¸ä¼ ä¿åå°æå¡å¨ä¸ã
ããå¨è¿å¨ä¸æè¡¥å
ä¿®æ£çHTML5ç驱å¨ä¸ï¼Web Appä¸Native Appä¹é´çè·ç¦»å°è¶æ¥è¶å°ãå¨å¯é¢è§çä¸è¿çæªæ¥ï¼è¶æ¥è¶å¤èçåæ°çå¼å项ç®å¿
å°ä¼è¿ç§»å°WEBåºç¨ä¸æ¥ã
ç¸å
³è§èï¼
The MediaCapture APIï¼
http://www.w3.org/TR/media-capture-api/Canvasï¼
http://dev.w3.org/html5/2dcontext/