C#运用GmaQrCode生成二维码

时间:2022-03-07 01:18:26

    项目中需要生成二维码,方法比较多,可以采用JS插件,也可以采用第三方插件后台生成二维码,在后台方法中可以采用QRCode或者GmaQrCode,现在介绍一种C#在后台生成二维码的方法:

   

        /// <summary>         /// 获取二维码         /// </summary>         /// <param name="codeString">编码字符</param>         /// <returns>二维码地址</returns>         public static string ReturnGmaQrCode(string codeString)         {             try             {                 using (var ms = new MemoryStream())                 {                     //const string stringtest = "中国ing?&";                     if (string.IsNullOrEmpty(codeString))                     {                         throw new ArgumentNullException(codeString);                     }                     var stringtest = codeString;                     CreateGmaQrCodeHelper(stringtest, ms);                     var img = Image.FromStream(ms);                     var filename = DateTime.Now.ToString("yyyymmddhhmmss");                     var path = HttpContext.Current.Server.MapPath("~/image/") + filename + ".png";                     img.Save(path);                     return path;                 }             }             catch (Exception ex)             {                 throw new Exception(ex.Message);             }         }         /// <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 CreateGmaQrCodeHelper(string strContent, MemoryStream ms)         {             try             {                 //误差校正水平                 const ErrorCorrectionLevel ecl = ErrorCorrectionLevel.M;                 //待编码内容                 var content = strContent;                 //空白区域                 const QuietZoneModules quietZones = QuietZoneModules.Two;                 //大小                 const 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;                 }             }             catch (Exception ex)             {                 throw new Exception(ex.Message);             }             return true;         }