HTML5网页扫描二维码

不多说,直接上代码

[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;
            }
        }
    }

解析图片用的 ZXing 的DLL,引用上之后就可以了,二维码格式自己定义,研究了几天,虽然大多数代码都不是自己写的

但是也有点收获,至少我的思路时没错的,大家觉得有用可以参考下,另外浏览器要支持HTML5,我用的是火狐浏览器,谢谢!


你可能感兴趣的:(HTML5网页扫描二维码)