Html
<div id="contentHolder"> <video id="video" width="320" height="320" autoplay> </video> <button id="snap" style="display: none"> 拍照 </button> <canvas style="display: none" id="canvas" width="320" height="320"> </canvas> </div> <div> <input type="button" value="拍照" onclick="CatchCode()" /></div>
Js
//这段代 主要是获取摄像头的视频流并显示在Video 签中 window.addEventListener("DOMContentLoaded", function () { 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); }; //navigator.getUserMedia这个写法在Opera中好像是navigator.getUserMedianow if (navigator.getUserMedia) { navigator.getUserMedia(videoObj, function (stream) { video.src = stream; video.play(); }, errBack); } else if (navigator.webkitGetUserMedia) { navigator.webkitGetUserMedia(videoObj, function (stream) { video.src = window.webkitURL.createObjectURL(stream); video.play(); }, errBack); } //这个是拍照按钮的事件, $("#snap").click(function () { context.drawImage(video, 0, 0, 320, 320); //CatchCode(); }); }, false); //这个是 刷新上 图像的 function CatchCode() { //$("#snap").click(); document.getElementById("canvas").getContext("2d").drawImage(video, 0, 0, 320, 320); //实际运用可不写,测试代 , 为单击拍照按钮就获取了当前图像,有其他用途 var canvans = document.getElementById("canvas"); //获取浏览器页面的画布对象 //以下开始编 数据 var imgData = canvans.toDataURL(); //将图像转换为base64数据 var base64Data = imgData.substr(22); //在前端截取22位之后的字符串作为图像数据 //开始异步上 $.post("Html5UseCamera.aspx?action=upload", { "img": base64Data }, function (data, status) { }, "text"); }
C#
byte[] imgBytes = Convert.FromBase64String(Request.Form["img"]); Stream stream = new MemoryStream(imgBytes); System.Drawing.Image image = System.Drawing.Image.FromStream(stream); image.Save(Server.MapPath("~/") + Guid.NewGuid().ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);