生成二維碼,幫助類:
using Gma.QrCodeNet.Encoding; using Gma.QrCodeNet.Encoding.Windows.Render; using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Piano.Utility.Common { public class QRCodeHelper { /// <summary> /// 獲取二維碼 /// </summary> /// <param name="strContent">待編碼的字符</param> /// <param name="ms">輸出流</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) { ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //誤差校正水平 string Content = strContent;//待編碼內容 QuietZoneModules QuietZones = QuietZoneModules.Two; //空白區域 int ModuleSize = 12;//大小 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; } } }
使用方法(此處是MVC5.2.0模式下):
//二維碼生成 public ActionResult getQrCode() { // Render the QR code as an image using (var ms = new MemoryStream()) { string url = string.Format(ConfigurationManager.AppSettings["WxgzhUrl"], UserValidator.GetInstituteId()); string stringtest = url; QRCodeHelper.GetQRCode(stringtest, ms); Response.ContentType = "image/Png"; Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length); Response.End(); } return View(); }
前端調用:
<img src="/My/getQrCode" alt="" style="width:160px;height:160px;" /><span class="remindmsg">掃一掃查看</span>