HTML5网页扫描二维码

2018-5-22    seo达人

如果您想订阅本博客内容,每天自动发到您的邮箱中, 请点这里

[HTML]代码

<!DOCTYPE html>
<html>
<head>
    <title>二维码扫描测试</title>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<style type="text/css">
    html, body {
        height: 100%;
        width: 100%;
        text-align: center;
    }
</style>
<script src="../js/jquery-1.11.1.min.js"></script>
<script>
    //这段代 主要是获取摄像头的视频流并显示在Video 签中
    var canvas = null, context = null, video = null;
    window.addEventListener("DOMContentLoaded", function () {
        try {
            canvas = document.getElementById("canvas");
            context = canvas.getContext("2d");
            video = document.getElementById("video");
            var videoObj = { "video": true, audio: false },
                flag = true,
                MediaErr = function (error) {
                    flag = false;
                    if (error.PERMISSION_DENIED) {
                        alert('用户拒绝了浏览器请求媒体的权限', '提示');
                    } else if (error.NOT_SUPPORTED_ERROR) {
                        alert('对不起,您的浏览器不支持拍照功能,请使用其他浏览器', '提示');
                    } else if (error.MANDATORY_UNSATISFIED_ERROR) {
                        alert('指定的媒体类型未接收到媒体流', '提示');
                    } else {
                        alert('系统未能获取到摄像头,请确保摄像头已正确安装。或尝试刷新页面,重试', '提示');
                    }
                };
            //获取媒体的兼容代码,目前只支持(Firefox,Chrome,Opera)
            if (navigator.getUserMedia) {
                //qq浏览器不支持
                if (navigator.userAgent.indexOf('MQQBrowser') > -1) {
                    alert('对不起,您的浏览器不支持拍照功能,请使用其他浏览器', '提示');
                    return false;
                }
                navigator.getUserMedia(videoObj, function (stream) {
                    video.src = stream;
                    video.play();
                }, MediaErr);
            }
            else if (navigator.webkitGetUserMedia) {
                navigator.webkitGetUserMedia(videoObj, function (stream) {
                    video.src = window.webkitURL.createObjectURL(stream);
                    video.play();
                }, MediaErr);
            }
            else if (navigator.mozGetUserMedia) {
                navigator.mozGetUserMedia(videoObj, function (stream) {
                    video.src = window.URL.createObjectURL(stream);
                    video.play();
                }, MediaErr);
            }
            else if (navigator.msGetUserMedia) {
                navigator.msGetUserMedia(videoObj, function (stream) {
                    $(document).scrollTop($(window).height());
                    video.src = window.URL.createObjectURL(stream);
                    video.play();
                }, MediaErr);
            } else {
                alert('对不起,您的浏览器不支持拍照功能,请使用其他浏览器');
                return false;
            }
            if (flag) {
                //alert('为了获得更准确的测试结果,请尽量将二维码置于框中,然后进行拍摄、扫描。 请确保浏览器有权限使用摄像功能');
            }
            //这个是拍照按钮的事件,
            $("#snap").click(function () { startPat(); }).show();
        } catch (e) {
            printHtml("浏览器不支持HTML5 CANVAS");
        }
    }, false);
    //打印内容到页面
    function printHtml(content) {
        $(window.document.body).append(content + "<br/>");
    }
    //开始拍照
    function startPat() {
        setTimeout(function () {//防止调用过快
            if (context) {
                context.drawImage(video, 0, 0, 320, 320);
                CatchCode();
            }
        }, 200);
    }
    //抓屏获取图像流,并上传到服务器
    function CatchCode() {
        if (canvas != null) {
            //以下开始编 数据
            var imgData = canvas.toDataURL("image/jpeg");
            //将图像转换为base64数据
            var base64Data = imgData; //在前端截取22位之后的字符串作为图像数据
            $.ajax({
                type: 'post',
                url: '../ashx/HandlerScan.ashx?method=ParseImage',
                data: 'ImgData=' + base64Data,
                dataType: "json",
                cache: false,
                timeout: 10000,
                success: function (mes) {
                    if (mes.code == '1') {
                        alert('未识别二维码,请重新扫描!');
                    }
                    else {
                        alert(mes.name);
                    }
                },
                error: function (err) {
                    alert('扫描失败' + err);
                }
            });
        }
    }
</script>
<body>
    <div id="support"></div>
    <div id="contentHolder">
        <video id="video" width="320" height="320" autoplay></video>
        <canvas id="canvas" style="display:none; background-color:#F00;" width="320" height="320"></canvas><br/>
        <button id="snap" style="display:none; height:50px; width:120px;">开始扫描</button>
    </div>
</body>
</html>  

[C#后台]

    public class HandlerScan : IHttpHandler
    {
        private JsonResult js = new JsonResult();
        public void ProcessRequest(HttpContext context)
        {
            string result = string.Empty;
            string method = context.Request.QueryString.ToString();//获取想要做的操作
            switch (method)
            {
                case "method=ParseImage":
                    result = ParseImage(context);
                    break;
                default:
                    break;
            }
            context.Response.ContentType = "text/json";
            context.Response.Write(result);
        }
        private string ParseImage(HttpContext context)
        {
            try
            {
                string imgStr = context.Request.Params["ImgData"].ToString();
                imgStr = imgStr.Replace("data:image/jpeg;base64,", "");
                //整理字符串
                imgStr = imgStr.Replace(" ", "+");
                byte[] arr = Convert.FromBase64String(imgStr);
                MemoryStream ms = new MemoryStream(arr, 0, arr.Length);
                Bitmap bmp = new Bitmap(ms);
                //解析图片
                Result result = new BarcodeReader().Decode(bmp);
                if(result == null)
                {
                    return "{\"code\":1,\"name\":\"\"}";
                }
                else
                {
                    string[] a = result.Text.Split(','); 
                    string str = "{\"code\":0,\"name\":\"" + a[0] + "\"}";
                    return str; 
                }
            }
            catch (Exception ex)
            {
                return "{\"code\":1,\"msg\":\"" + ex.Message + "\",\"userName\":\"\"}";
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
蓝蓝设计www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、 网站建设 平面设计服务

日历

链接

个人资料

蓝蓝设计的小编 http://www.lanlanwork.com

存档