基于ZXing.NET实现的二维码生成和识别客户端

  • 基于ZXing.NET实现的二维码生成和识别客户端已关闭评论
  • 107 次浏览
  • A+
所属分类:.NET技术
摘要

ZXing.Net的一个可移植软件包,是一个开源的、多格式的1D/2D条形码图像处理库,最初是用Java实现的。已经过大量优化和改进,它已经被手动移植。它与.Net 2.0、.Net 3.5、.Net 4.x、.Net 5.x、.Net 6.x、.Net 7.x、Windows RT类库和组件、UWP、.Net Standard 1.x和2.0x、.Net Core App 3.x、Silverlight 4、Silverlight 5、Windows Phone 7.x和Windows Phone 8.x以及Xamarin.Android兼容。


一、前言

ZXing.Net的一个可移植软件包,是一个开源的、多格式的1D/2D条形码图像处理库,最初是用Java实现的。已经过大量优化和改进,它已经被手动移植。它与.Net 2.0、.Net 3.5、.Net 4.x、.Net 5.x、.Net 6.x、.Net 7.x、Windows RT类库和组件、UWP、.Net Standard 1.x和2.0x、.Net Core App 3.x、Silverlight 4、Silverlight 5、Windows Phone 7.x和Windows Phone 8.x以及Xamarin.Android兼容。

二、项目环境和搭建

项目框架:.NET Framework 4.6.1

项目依赖:ZXing.Net

基于ZXing.NET实现的二维码生成和识别客户端

项目结构和界面设计

基于ZXing.NET实现的二维码生成和识别客户端

三、实现核心代码

ZXing帮助类

 /// <summary>  /// ZXing.NET 二维码帮助类  /// </summary>  public class ZXingHelper  {       /// <summary>      /// 站点二维码的目录      /// </summary>      private static string QRCodeDirectory = "QRCode";      /// <summary>      /// 使用zxing动态库生成二维码      /// </summary>      /// <param name="conetnt">二维码内容</param>      /// <param name="errorMessage">异常信息</param>      /// <param name="logoPath">logo图片路径,默认为空。为空时生成的二维码不带logo</param>      /// <param name="height">二维码图片高度,默认240 单位 pixels</param>      /// <param name="width">二维码图片宽度,默认240 单位 pixels</param>      /// <param name="margin">二维码图片边距,默认为0</param>      /// <returns></returns>      public static Bitmap GenerateQRCode(string conetnt, out string errorMessage, string logoPath = "", int height = 240, int width = 240, int margin = 0)      {          errorMessage = string.Empty;          try          {              BarcodeWriter barCodeWriter = new BarcodeWriter();              barCodeWriter.Format = BarcodeFormat.QR_CODE;              barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");              barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);              barCodeWriter.Options.Height = height;              barCodeWriter.Options.Width = width;              barCodeWriter.Options.Margin = margin;              BitMatrix bm = barCodeWriter.Encode(conetnt);              Bitmap qrCodeImage = barCodeWriter.Write(bm);               if (!string.IsNullOrEmpty(logoPath))              {                  // 添加Logo                  Bitmap logo = new Bitmap(logoPath);                  int logoSize = (int)(qrCodeImage.Width * 0.2); // Logo大小为二维码大小的1/5                  int logoX = (qrCodeImage.Width - logoSize) / 2;                  int logoY = (qrCodeImage.Height - logoSize) / 2;                   Graphics qrGraphics = Graphics.FromImage(qrCodeImage);                  qrGraphics.DrawImage(logo, new Rectangle(logoX, logoY, logoSize, logoSize));              }               return qrCodeImage;          }          catch (Exception ex)          {              errorMessage = $"Exception raised when generating QRCode,, Exception;{ex}";              return null;          }      }       /// <summary>      /// 使用zxing动态库解析:二维码,条形码......      /// </summary>      /// <param name="image">二维码图像</param>      /// <returns></returns>      public static string ParseBarCode(Bitmap image)      {          BarcodeReader reader = new BarcodeReader();          Result result = reader.Decode(image);          return result.Text;      }       /// <summary>      /// 使用zxing动态库生成二维码      /// </summary>      /// <param name="conetnt">二维码内容</param>      /// <param name="logoPath">logo图片路径,默认为空。为空时生成的二维码不带logo</param>      /// <param name="height">二维码图片高度,默认240 单位 pixels</param>      /// <param name="width">二维码图片宽度,默认240 单位 pixels</param>      /// <param name="margin">二维码图片边距,默认为0</param>      /// <returns></returns>      public static void GenerateQRCode(string conetnt, string logoPath = "", int height = 240, int width = 240, int margin = 0)      {          try          {              BarcodeWriter barCodeWriter = new BarcodeWriter();              barCodeWriter.Format = BarcodeFormat.QR_CODE;              barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");              barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);              barCodeWriter.Options.Height = height;              barCodeWriter.Options.Width = width;              barCodeWriter.Options.Margin = margin;              BitMatrix bm = barCodeWriter.Encode(conetnt);              Bitmap qrCodeImage = barCodeWriter.Write(bm);               if (!string.IsNullOrEmpty(logoPath))              {                  // 添加Logo                  Bitmap logo = new Bitmap(logoPath);                  int logoSize = (int)(qrCodeImage.Width * 0.2); // Logo大小为二维码大小的1/5                  int logoX = (qrCodeImage.Width - logoSize) / 2;                  int logoY = (qrCodeImage.Height - logoSize) / 2;                   Graphics qrGraphics = Graphics.FromImage(qrCodeImage);                  qrGraphics.DrawImage(logo, new Rectangle(logoX, logoY, logoSize, logoSize));              }              string qrCodeFile = AppDomain.CurrentDomain.BaseDirectory + QRCodeDirectory + "/" + "qrcode.jpg";              if (File.Exists(qrCodeFile))              {                  File.Delete(qrCodeFile);              }              qrCodeImage.Save(qrCodeFile, System.Drawing.Imaging.ImageFormat.Jpeg);//保存二维码图片          }          catch (Exception ex)          {           }      }  } 

选择logo

    /// <summary>     /// 选择logo     /// </summary>     /// <param name="sender"></param>     /// <param name="e"></param>     private void btn_selectlogo_Click(object sender, EventArgs e)     {         try         {             OpenFileDialog openFileDialog = new OpenFileDialog();             openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//初始路径为桌面             openFileDialog.Filter = "Logo图片|*.png;*.jpg;*.jpeg;*.ico";             if (openFileDialog.ShowDialog() == DialogResult.OK)             {                 picLogo.Image = Image.FromFile(openFileDialog.FileName);                 logPath = openFileDialog.FileName;//logo文件路径             }         }         catch (Exception ex)         {             MessageBox.Show(ex.Message);         }      } 

生成二维码

  /// <summary>   /// 生成二维码   /// </summary>   /// <param name="sender"></param>   /// <param name="e"></param>   private void bt_generate_Click(object sender, EventArgs e)   {       try       {           string errorMsg = "";           string content = rtbQRCodeContent.Text;           if (string.IsNullOrWhiteSpace(content))           {               MessageBox.Show("二维码内容不能为空!");               return;           }            picQRCode.Image = ZXingHelper.GenerateQRCode(content, out errorMsg, logPath);           if (!string.IsNullOrWhiteSpace(errorMsg))           {               MessageBox.Show(errorMsg);           }       }       catch (Exception ex)       {           MessageBox.Show(ex.Message);       }   } 

识别二维码

  /// <summary>   /// 识别二维码   /// </summary>   /// <param name="sender"></param>   /// <param name="e"></param>   private void btn_identityQrCode_Click(object sender, EventArgs e)   {       try       {           if (picQRCode.Image == null)           {               MessageBox.Show("请先生成二维码!");               return;           }           Bitmap Imagemap = new Bitmap(picQRCode.Image);           string QRCodeResult = ZXingHelper.ParseBarCode(Imagemap);           rtbQRCodeResult.Text = QRCodeResult;       }       catch (Exception ex)       {           MessageBox.Show(ex.Message);       }   }  

保存二维码

  /// <summary>   /// 保存二维码   /// </summary>   /// <param name="sender"></param>   /// <param name="e"></param>   private void btn_save_Click(object sender, EventArgs e)   {       try       {           if (picQRCode.Image == null)           {               MessageBox.Show("请先生成二维码!");               return;           }           SaveFileDialog saveFileDialog = new SaveFileDialog();           saveFileDialog.Filter = "保存图片|*.png;*.jpg;*.jpeg";           if (saveFileDialog.ShowDialog() == DialogResult.OK)           {               picQRCode.Image.Save(saveFileDialog.FileName, ImageFormat.Png);               MessageBox.Show("保存成功!");           }       }       catch (Exception ex)       {           MessageBox.Show(ex.Message);       }   } 

四、实现演示

基于ZXing.NET实现的二维码生成和识别客户端

五、源码工具获取

关注公众号,后台回复关键字:二维码工具