1.引用ThoughtWorks.QRCode.dll
在nuget上查找即可引用,也可自行下载
2.生成二维码静态方法
参数:
二维码内容:fileUrl
二维码图片名:typeName
#region 生成二维码图片 /// <summary> /// 生成二维码图片 /// </summary> /// <returns>上传图片路径</returns> public static string UploadQRCodeImage(string fileUrl, string typeName) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); String encoding = "Byte"; if (encoding == "Byte") { qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; } else if (encoding == "AlphaNumeric") { qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC; } else if (encoding == "Numeric") { qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC; } try { int scale = 3; qrCodeEncoder.QRCodeScale = scale; } catch (Exception ex) { // return; } try { int version = 0;//出现数组溢出问题,使用0会自动检测,使得encode通过 qrCodeEncoder.QRCodeVersion = version; } catch (Exception ex) { // MessageBox.Show("Invalid version !"); } string errorCorrect = "H"; if (errorCorrect == "L") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L; else if (errorCorrect == "M") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; else if (errorCorrect == "Q") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q; else if (errorCorrect == "H") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; Image image; // String data = fileUrl; image = qrCodeEncoder.Encode(fileUrl); //上传目录 string directory = HttpContext.Current.Server.MapPath(QRCodePath); string fileName = typeName + ".png";// + fileUrl.Split('.').Last(); if (!String.IsNullOrEmpty(fileName)) { //文件全路径 string path = directory + fileName; //判断目录是否存在 if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } //文件存在就删除文件 // AccessoryAPPI.DeleteFiles(path);//个人类库方法,仅作记录 File.Delete(path);
image.Save(path); } return ""; } #endregion
3.扩展
a.该方法可以直接返回path,即二维码图片路径;
b.如果使用.NET 4.0 会遇到展示的安全限制问题,可参考下文,返回base64图片;
http://www.cnblogs.com/xcsn/p/5278362.html