使用QRCode生成二维码

第一步: 获取QRCode组件

  可以通过vs的nuget管理安装Gma.QrCodeNet,

  也可以直接添加"Gma.QrCodeNet.Encoding.dll"的引用.

 

第二步:封装操作方法,编写QRCodeHelper帮助类(直接复制,黏贴即可)

 1  /// <summary>  
 2     /// 含有QR码的描述类和包装编码和渲染  
 3     /// </summary>  
 4     public class QRCodeHelper
 5     {
 6         /// <summary>  
 7         /// 获取二维码  
 8         /// </summary>  
 9         /// <param name="strContent">待编码的字符</param>  
10         /// <param name="ms">输出流</param>  
11         /// <param name="moduleSize">大小</param>  
12         ///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>  
13         public static bool GetQRCode(string strContent,MemoryStream ms, int moduleSize = 12)
14         {
15             ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平   
16             string Content = strContent;//待编码内容  
17             QuietZoneModules QuietZones = QuietZoneModules.Two;  //空白区域   
18             var encoder = new QrEncoder(Ecl);
19             QrCode qr;
20             if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵  
21             {
22                 var render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZones));
23                 render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
24             }
25             else
26             {
27                 return false;
28             }
29             return true;
30         }
31 
32     }  

 

第三步: 测试调用,生成二维码图片

1 using (var ms = new MemoryStream())
2 {
3     string strContent = "http://www.baidu.com";
4     QRCodeHelper.GetQRCode(strContent, ms, 12);
5     Response.ContentType = "image/Png";
6     Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
7     Response.End();
8 }

 

补充:

  如果想通过js动态生成二维码,可使用jQuery.QRCode插件.说明文档:  https://larsjung.de/jquery-qrcode/

  

  QRCode组件下载地址: https://pan.baidu.com/s/1slMrQHJ

 

posted @ 2016-11-16 16:54  秒杀5S  阅读(503)  评论(0编辑  收藏  举报