您的位置:首页 > 其它

使用QRCode生成二维码

2016-11-16 16:54 405 查看
第一步: 获取QRCode组件

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

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

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

/// <summary>
/// 含有QR码的描述类和包装编码和渲染
/// </summary>
public class QRCodeHelper
{
/// <summary>
/// 获取二维码
/// </summary>
/// <param name="strContent">待编码的字符</param>
/// <param name="ms">输出流</param>
/// <param name="moduleSize">大小</param>
///<returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
public static bool GetQRCode(string strContent,MemoryStream ms, int moduleSize = 12)
{
ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平
string Content = strContent;//待编码内容
QuietZoneModules QuietZones = QuietZoneModules.Two;  //空白区域
var encoder = new QrEncoder(Ecl);
QrCode qr;
if (encoder.TryEncode(Content, out qr))//对内容进行编码,并保存生成的矩阵
{
var render = new GraphicsRenderer(new FixedModuleSize(moduleSize, QuietZones));
render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
}
else
{
return false;
}
return true;
}

}


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

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


补充:

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

  QRCode组件下载地址: https://pan.baidu.com/s/1slMrQHJ
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: