前台代码:
<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>
JS代码:
<script> //这段代 主要是获取摄像头的视频流并显示在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); //定时器 var interval = setInterval(CatchCode, "300"); //这个是 刷新上 图像的 function CatchCode() { $("#snap").click(); //实际运用可不写,测试代 , 为单击拍照按钮就获取了当前图像,有其他用途 var canvans = document.getElementById("canvas"); //获取浏览器页面的画布对象 //以下开始编 数据 var imgData = canvans.toDataURL(); //将图像转换为base64数据 var base64Data = imgData.substr(22); //在前端截取22位之后的字符串作为图像数据 //开始异步上 $.post("uploadImgCode.ashx", { "img": base64Data }, function (data, status) { if (status == "success") { if (data == "OK") { alert("二维 已经解析"); } else { // alert(data); } } else { alert("数据上 失败"); } }, "text"); } </script>
后台代码:
public void ProcessRequest (HttpContext context) { string img;//接收经过base64编 之后的字符串 context.Response.ContentType = "text/plain"; try { img =context.Request["img"].ToString(); //获取base64字符串 byte[] imgBytes = Convert.FromBase64String(img); //将base64字符串转换为字节数组 System.IO.Stream stream = new System.IO.MemoryStream(imgBytes); //将字节数组转换为字节流 //将流转回Image,用于将PNG 式照片转为jpg,压缩体积以便保存。 System.Drawing.Image imgae = System.Drawing.Image.FromStream(stream); imgae.Save(context.Server.MapPath("~/Test/") + Guid.NewGuid().ToString()+".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);//保存图片 context.Response.Write("OK");//输出调用结果 } catch (Exception msg) { img = null; context.Response.Write(msg); return; } }
代码来源:http://bbs.9ria.com/thread-215588-1-1.html