一切福田,不離方寸,從心而覓,感無不通。

ASP.NET实现二维码(QRCode)的创建和读取

QR二维码比其他二维码相比,具有识读速度快、数据密度大、占用空间小的优势。QR码的三个角上有三个寻象图形,使用CCD识读设备来探测码的位置、大小、倾斜角度、并加以解码,实现360度高速识读。每秒可以识读30个含有100个字符QR码。QR码容量密度 大,可以放入1817个汉字、7089个数字、4200个英文字母。QR码用数据压缩方式表示汉字,仅用13bit即可表示一个汉字,比其他二维条码表示汉字的效率提高了20%。QR具有4个等级的纠错功能,即使破损也能够正确识读。QR码抗弯曲的性能强,通过QR码中的每隔一定的间隔配置有校正图形,从码的外形来求得推测校正图形中心点与实际校正图形中心点的误差来修正各个模快的中心距离,即使将QR码贴在弯曲的物品上也能够快速识读。QR码可以分割成16个QR码,可以一次性识读数个分割码,适应于印刷面积有限及细长空间印刷的需要。此外微型QR码可以在1厘米的空间内放入35个数字或9个汉字或21个英文字母,适合对小型电路板对ID号码进行采集的需要。(From:http://tuqiang9999.blog.163.com/blog/static/33241320111115103159542/
QRCode下载地址:ThoughtWorks.QRCode(支持中文)

 

一、项目引用QRCode的DLL文件(ThoughtWorks.QRCode.dll)

二、ASPX页面(两个jquery的js文件请自行去官网下载):

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3.     <title>二维码工具测试</title>
  4.     <script type="text/javascript" src="../../Scripts/Jquery/jquery-1.6.2.js"></script>
  5.     <script type="text/javascript" src="../../Scripts/Jquery/jquery.form.js"></script>
  6.     <script type="text/javascript" src="js/test.js"></script>
  7.     <style type="text/css">
  8.         .style1
  9.         {
  10.             width: 100%;
  11.         }
  12.         #txt_qr
  13.         {
  14.             width: 632px;
  15.         }
  16.     </style>
  17. </head>
  18. <body>
  19.     <div>
  20.         <table class="style1">
  21.             <tr>
  22.                 <td>
  23.                     输入文字:
  24.                 </td>
  25.                 <td>
  26.                     <input type="text" id="txt_qr" name="txt_qr" />
  27.                 </td>
  28.             </tr>
  29.             <tr>
  30.                 <td>
  31.                     二维码图片
  32.                 </td>
  33.                 <td>
  34.                     <img id="qrimg" alt="二维码图片" />
  35.                 </td>
  36.             </tr>
  37.             <tr>
  38.                 <td>
  39.                     生成选项
  40.                 </td>
  41.                 <td>
  42.                     Encoding:<select id="Encoding">
  43.                         <option value="Byte">Byte</option>
  44.                         <option value="AlphaNumeric">AlphaNumeric</option>
  45.                         <option value="Numeric">Numeric</option>
  46.                     </select>
  47.                     Correction Level:<select id="Level">
  48.                         <option value="M">M</option>
  49.                         <option value="L">L</option>
  50.                         <option value="Q">Q</option>
  51.                         <option value="H">H</option>
  52.                     </select>
  53.                     Version:<input id="txt_ver" type="text" value="7" />(1-40) Size:<input id="txt_size"
  54.                         type="text" value="4" />
  55.                 </td>
  56.             </tr>
  57.             <tr>
  58.                 <td colspan="4">
  59.                     <input type="button" onclick="getQrImg();" value="生成二维码" />
  60.                 </td>
  61.             </tr>
  62.             <tr>
  63.                 <td>
  64.                     <form id="qrForm" action="Ashx/test.ashx" method="post" enctype="multipart/form-data">
  65.                     <input type="file" id="file_qr" name="file_qr" /><input type="submit" value="读取二维码" />
  66.                     </form>
  67.                 </td>
  68.                 <td colspan="1">
  69.                     <img id="img_qr" alt="要读取的图片" /><br />
  70.                     <input id="txt_readqr" type="text" />
  71.                 </td>
  72.             </tr>
  73.         </table>
  74.     </div>
  75. </body>
  76. </html>

三、test.js文件

[javascript]

  1. $(document).ready(function ()
  2. {
  3.     var options = {
  4.         beforeSubmit: showRequest,
  5.         success: showResponse,
  6.         dataType: 'json',
  7.         clearForm: true,
  8.         error: function (request, message, ex)
  9.         {
  10.             alert('错误:' + message);
  11.         }
  12.     };
  13.     $('#qrForm').ajaxForm(options);
  14. });
  15. function showRequest(formData, jqForm, options)
  16. {
  17.     return true;
  18. }
  19. function showResponse(responseText, statusText, xhr, $form)
  20. {
  21.     if (responseText[0].count == 0)
  22.     {
  23.         alert(responseText[0].list[0].error);
  24.         return false;
  25.     }
  26.     $("#img_qr").attr("src", responseText[0].list[0].imgurl);
  27.     $("#txt_readqr").val(responseText[0].list[0].qrtext);
  28.     return false;
  29. }
  30. function getQrImg()
  31. {
  32.     var txt_qr = escape($.trim($("#txt_qr").val()));
  33.     var qrEncoding = $("#Encoding").val(); ;
  34.     var Level = $("#Level").val(); ;
  35.     var txt_ver = $("#txt_ver").val(); ;
  36.     var txt_size = $("#txt_size").val(); ;
  37.     $.ajax({
  38.         type: "GET",
  39.         data: "cmd=set&txt_qr=" + txt_qr + "&qrEncoding=" + qrEncoding + "&Level=" + Level + "&txt_ver=" + txt_ver + "&txt_size=" + txt_size,
  40.         url: "Ashx/test.ashx",
  41.         dataType: 'text',
  42.         beforeSend: function (x)
  43.         {
  44.             x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
  45.         },
  46.         success: function (json)
  47.         {
  48.             var dataObj = eval(json);
  49.             $("#qrimg").attr("src", dataObj[0].list[0].imgurl);
  50.             return false;
  51.         },
  52.         error: function (request, message, ex)
  53.         {
  54.             alert("错误:" + message);
  55.         }
  56.     });
  57. }

四、test.ashx,没有判断目录是否存在等问题,请自行建立或者更改代码。

[csharp]

  1. using System;
  2. using System.Web;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using ThoughtWorks.QRCode.Codec;
  8. using ThoughtWorks.QRCode.Codec.Data;
  9. using ThoughtWorks.QRCode.Codec.Util;
  10. public class test : IHttpHandler
  11. {
  12.     public void ProcessRequest(HttpContext context)
  13.     {
  14.         context.Response.ContentType = "text/plain";
  15.         string cmd = context.Request["cmd"] == null ? "get" : context.Request["cmd"].ToString();
  16.         string filename = string.Empty;
  17.         string filepath = string.Empty;
  18.         switch (cmd)
  19.         {
  20.             case "get":
  21.                 if (context.Request.Files.Count > 0)
  22.                 {
  23.                     for (int j = 0; j < context.Request.Files.Count; j++)
  24.                     {
  25.                         filename = Guid.NewGuid().ToString() + "_tmp.jpg";
  26.                         filepath = context.Server.MapPath(@"~\Utilty\QRCode\upload") + "\\" + filename;
  27.                         string qrdecode = string.Empty;
  28.                         HttpPostedFile uploadFile = context.Request.Files[j];
  29.                         uploadFile.SaveAs(filepath);
  30.                         QRCodeDecoder decoder = new QRCodeDecoder();
  31.                         Bitmap bm = new Bitmap(filepath);
  32.                         qrdecode = decoder.decode(new QRCodeBitmapImage(bm));
  33.                         bm.Dispose();
  34.                         context.Response.Write("[{\"count\":1,\"list\":[{\"imgurl\":\"upload/" + filename + "\",\"qrtext\":\"" + qrdecode + "\"}]}]");
  35.                     }
  36.                 }
  37.                 else
  38.                 {
  39.                     context.Response.Write("[{\"count\":0,\"list\":[{\"error\":\"没有上传文件\"}]}]");
  40.                 }
  41.                 break;
  42.             case "set":
  43.                 string txt_qr =ConverToGB(context.Request["txt_qr"].ToString().Trim(), 16);
  44.                 string qrEncoding = context.Request["qrEncoding"].ToString();
  45.                 string Level = context.Request["Level"].ToString();
  46.                 string txt_ver = context.Request["txt_ver"].ToString();
  47.                 string txt_size = context.Request["txt_size"].ToString();
  48.                 QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
  49.                 String encoding = qrEncoding;
  50.                 if (encoding == "Byte")
  51.                 {
  52.                     qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
  53.                 }
  54.                 else if (encoding == "AlphaNumeric")
  55.                 {
  56.                     qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
  57.                 }
  58.                 else if (encoding == "Numeric")
  59.                 {
  60.                     qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
  61.                 }
  62.                 try
  63.                 {
  64.                     int scale = Convert.ToInt16(txt_size);
  65.                     qrCodeEncoder.QRCodeScale = scale;
  66.                 }
  67.                 catch (Exception ex)
  68.                 {
  69.                     return;
  70.                 }
  71.                 try
  72.                 {
  73.                     int version = Convert.ToInt16(txt_ver);
  74.                     qrCodeEncoder.QRCodeVersion = version;
  75.                 }
  76.                 catch (Exception ex)
  77.                 {
  78.                     return;
  79.                 }
  80.                 string errorCorrect = Level;
  81.                 if (errorCorrect == "L")
  82.                     qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
  83.                 else if (errorCorrect == "M")
  84.                     qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
  85.                 else if (errorCorrect == "Q")
  86.                     qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
  87.                 else if (errorCorrect == "H")
  88.                     qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
  89.                 Image image;
  90.                 String data = txt_qr;
  91.                 image = qrCodeEncoder.Encode(data);
  92.                 filename = Guid.NewGuid().ToString() + ".jpg";
  93.                 filepath = context.Server.MapPath(@"~\Utilty\QRCode\upload") + "\\" + filename;
  94.                 System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
  95.                 image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
  96.                 fs.Close();
  97.                 image.Dispose();
  98.                 context.Response.Write("[{\"count\":1,\"list\":[{\"imgurl\":\"upload/" + filename + "\"}]}]");
  99.                 //context.Response.Write(@"upload\" + filename);
  100.                 break;
  101.         }
  102.     }
  103.     /// <summary>
  104.     /// 10进制或16进制转换为中文
  105.     /// </summary>
  106.     /// <param name="name">要转换的字符串</param>
  107.     /// <param name="fromBase">进制(10或16)</param>
  108.     /// <returns></returns>
  109.     public string ConverToGB(string text, int fromBase)
  110.     {
  111.         string value = text;
  112.         MatchCollection mc;
  113.         System.Text.StringBuilder sb = new System.Text.StringBuilder();
  114.         switch (fromBase)
  115.         {
  116.             case 10:
  117.                 MatchCollection mc1 = Regex.Matches(text, @"&#([\d]{5})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  118.                 foreach (Match _v in mc1)
  119.                 {
  120.                     string w = _v.Value.Substring(2);
  121.                     w = Convert.ToString(int.Parse(w), 16);
  122.                     byte[] c = new byte[2];
  123.                     string ss = w.Substring(0, 2);
  124.                     int c1 = Convert.ToInt32(w.Substring(0, 2), 16);
  125.                     int c2 = Convert.ToInt32(w.Substring(2), 16);
  126.                     c[0] = (byte)c2;
  127.                     c[1] = (byte)c1;
  128.                     sb.Append(Encoding.Unicode.GetString(c));
  129.                 }
  130.                 value = sb.ToString();
  131.                 break;
  132.             case 16:
  133.                 mc = Regex.Matches(text, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  134.                 if (mc != null && mc.Count > 0)
  135.                 {
  136.                     foreach (Match m2 in mc)
  137.                     {
  138.                         string v = m2.Value;
  139.                         string w = v.Substring(2);
  140.                         byte[] c = new byte[2];
  141.                         int c1 = Convert.ToInt32(w.Substring(0, 2), 16);
  142.                         int c2 = Convert.ToInt32(w.Substring(2), 16);
  143.                         c[0] = (byte)c2;
  144.                         c[1] = (byte)c1;
  145.                         sb.Append(Encoding.Unicode.GetString(c));
  146.                     }
  147.                     value = sb.ToString();
  148.                 }
  149.                 break;
  150.         }
  151.         return value;
  152.     }
  153.     public bool IsReusable
  154.     {
  155.         get
  156.         {
  157.             return false;
  158.         }
  159.     }
  160. }

 

 转自:http://blog.csdn.net/5653325/article/details/8556760