HTML5網(wǎng)頁(yè)掃描二維碼

2018-5-22    seo達(dá)人

如果您想訂閱本博客內(nèi)容,每天自動(dòng)發(fā)到您的郵箱中, 請(qǐng)點(diǎn)這里

[HTML]代碼

<!DOCTYPE html>
<html>
<head>
    <title>二維碼掃描測(cè)試</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('用戶拒絕了瀏覽器請(qǐng)求媒體的權(quán)限', '提示');
                    } else if (error.NOT_SUPPORTED_ERROR) {
                        alert('對(duì)不起,您的瀏覽器不支持拍照功能,請(qǐng)使用其他瀏覽器', '提示');
                    } else if (error.MANDATORY_UNSATISFIED_ERROR) {
                        alert('指定的媒體類(lèi)型未接收到媒體流', '提示');
                    } else {
                        alert('系統(tǒng)未能獲取到攝像頭,請(qǐng)確保攝像頭已正確安裝。或嘗試刷新頁(yè)面,重試', '提示');
                    }
                };
            //獲取媒體的兼容代碼,目前只支持(Firefox,Chrome,Opera)
            if (navigator.getUserMedia) {
                //qq瀏覽器不支持
                if (navigator.userAgent.indexOf('MQQBrowser') > -1) {
                    alert('對(duì)不起,您的瀏覽器不支持拍照功能,請(qǐng)使用其他瀏覽器', '提示');
                    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('對(duì)不起,您的瀏覽器不支持拍照功能,請(qǐng)使用其他瀏覽器');
                return false;
            }
            if (flag) {
                //alert('為了獲得更準(zhǔn)確的測(cè)試結(jié)果,請(qǐng)盡量將二維碼置于框中,然后進(jìn)行拍攝、掃描。 請(qǐng)確保瀏覽器有權(quán)限使用攝像功能');
            }
            //這個(gè)是拍照按鈕的事件,
            $("#snap").click(function () { startPat(); }).show();
        } catch (e) {
            printHtml("瀏覽器不支持HTML5 CANVAS");
        }
    }, false);
    //打印內(nèi)容到頁(yè)面
    function printHtml(content) {
        $(window.document.body).append(content + "<br/>");
    }
    //開(kāi)始拍照
    function startPat() {
        setTimeout(function () {//防止調(diào)用過(guò)快
            if (context) {
                context.drawImage(video, 0, 0, 320, 320);
                CatchCode();
            }
        }, 200);
    }
    //抓屏獲取圖像流,并上傳到服務(wù)器
    function CatchCode() {
        if (canvas != null) {
            //以下開(kāi)始編 數(shù)據(jù)
            var imgData = canvas.toDataURL("image/jpeg");
            //將圖像轉(zhuǎn)換為base64數(shù)據(jù)
            var base64Data = imgData; //在前端截取22位之后的字符串作為圖像數(shù)據(jù)
            $.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('未識(shí)別二維碼,請(qǐng)重新掃描!');
                    }
                    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;">開(kāi)始掃描</button>
    </div>
</body>
</html>  

[C#后臺(tái)]

    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;
            }
        }
    }
藍(lán)藍(lán)設(shè)計(jì)bouu.cn )是一家專(zhuān)注而深入的界面設(shè)計(jì)公司,為期望卓越的國(guó)內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù)

分享本文至:

日歷

鏈接

個(gè)人資料

存檔