基于html5、JS实现的二维码扫码

28 篇文章 0 订阅
11 篇文章 0 订阅

原理:调出摄像头,拍照保存到画布,定时传送到解析函数


说明:解析函数是后台c# .net MVC 实现的,解析函数用到的二维码解析API依赖于第三方二维码库google zxing , 因此需要先引用类库:zxing.dll、zxing.presentation.dll,如果你在网上找到可以用JS解析的麻烦留言相告,因为用JS解析是最好的方法,不用每次定时的发出http请求,也可以不用引入google zxing,不用c# .net MVC后台去解析,这样是最好的,但目前在网上找到的二维码扫描多数是用flash实现的,flash这种东西适用于PC端,却无法再android, iphone等移动终端上正常显示,即使正常,还要用户安装adobe flash插件才可以扫描,即使可以扫描,内存代价也比较高,如果你了解二维码原理,并想自己翻译这个解析算法,可以参考以下网址:

js二维码生成(没有解析函数):https://github.com/davidshimjs/qrcodejs

clouda+ (百度的JS端能力,目前已经有二维码扫描控件,可以分析它的原理):http://clouda.baidu.com/

PC端上的h5、js二维码生成及扫描解析:https://github.com/LazarSoft/jsqrcode


前端代码(QRcodeDecode.cshtml):

<style>#video {display: block;margin:1em auto;width:180px;height:180px;}</style>  
<video id="video" autoplay></video>
<script>
    window.addEventListener("DOMContentLoaded", function () {
        var video = document.getElementById("video"), canvas, context;
        try {
            canvas = document.createElement("canvas");
            context = canvas.getContext("2d");
        } catch (e) { alert("not support canvas!"); return; }
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;


        if (navigator.getUserMedia)
            navigator.getUserMedia(
                { "video": true },
                function (stream) {
                    if (video.mozSrcObject !== undefined)video.mozSrcObject = stream;
                    else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream;               
                    video.play();
                },
                function (error) {
                    //if(error.PERMISSION_DENIED)console.log("用户拒绝了浏览器请求媒体的权限",error.code);
                    //if(error.NOT_SUPPORTED_ERROR)console.log("当前浏览器不支持拍照功能",error.code);
                    //if(error.MANDATORY_UNSATISFIED_ERROR)console.log("指定的媒体类型未接收到媒体流",error.code);
                    alert("Video capture error: " + error.code);
                }
            );
        else alert("Native device media streaming (getUserMedia) not supported in this browser");
       


        setInterval(function () {
            context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight);
            $.post('/Home/QRcodeDecode', { "img": canvas.toDataURL().substr(22) }, function (data, status) {
                if (status == "success" && data != "no")location.href = "/Home/Result/" + data;               
            }, "text");
        }, 500);


    }, false);
 </script> 


后台代码(HomeController.cs):

using System;
using System.Drawing;
using System.IO;
using System.Web.Mvc;
using ZXing;


namespace WebFrame.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult QRcodeDecode(){ return View();}


        [HttpPost]
        public ActionResult QRcodeDecode(FormCollection form)
        {
            try{
                byte[] imgBytes = Convert.FromBase64String(form["img"]);        
                Stream stream = new MemoryStream(imgBytes);
                Result result = new BarcodeReader().Decode(new Bitmap(stream));
                return Content(Uri.EscapeDataString(result.Text));
            }catch{ return Content("no");}
        }


        public ActionResult Result(string id) { return View(); }
    }
}


以下是在android UC浏览器上看到的效果,打开测试页面,扫描带"hello Kitty !"的二维码

(带"hello Kitty !"的二维码):



识别成功效果图




附上Demo下载地址:html5二维码扫描   (含zxing.dll、zxing.presentation.dll、完整示例项目)

作为辛苦劳动成果,设置了3分滴下载小费,没分的筒鞋想办法获取积分,好的社区需要大家一同建设,杜绝伸手党


注:部分新手下载后不会使用,在此特别说明下,本工程使用VS2013或VS2012打开,运行一般能成功,若提醒错误的,提醒哪行出错就注释掉哪行就可以了,然后这个站点布署到IIS上,用手机访问入口地址:“/Home/QRcodeDecode”,此时就会显示调用手机设备授权了。


Android、IOS 内置浏览器上展示未测试,估计也是没问题滴,不过一般Android、IOS都用自己API实现扫码的,之所以还用h5,就是给浏览器扫码使用的,如果你有更好的方法或其它问题可以留言,大家共同探讨,共同学习。

评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值