基于ZXing.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兼容。

二、项目环境和搭建

项目框架:.NET Framework 4.6.1

项目依赖ZXing.Net

项目结构和界面设计

三、实现核心代码

ZXing帮助类

C# 复制代码
 /// <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

c# 复制代码
    /// <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);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

生成二维码

C# 复制代码
  /// <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);
          if (!string.IsNullOrWhiteSpace(errorMsg))
          {
              MessageBox.Show(errorMsg);
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message);
      }
  }

识别二维码

C# 复制代码
  /// <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);
      }
  }

保存二维码

C# 复制代码
  /// <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);
      }
  }

四、实现演示

五、源码工具获取

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

相关推荐
liyongqiangcc4 小时前
了解 ASP.NET Core 中的中间件
.net
Kiros_Jiang8 小时前
开源低代码平台-Microi吾码 打印引擎使用
javascript·开源·json·.net·pip
web1478621072311 小时前
C# .Net Web 路由相关配置
前端·c#·.net
数据的世界011 天前
.NET开发人员学习书籍推荐
学习·.net
paixiaoxin1 天前
CV-OCR经典论文解读|An Empirical Study of Scaling Law for OCR/OCR 缩放定律的实证研究
人工智能·深度学习·机器学习·生成对抗网络·计算机视觉·ocr·.net
1900431 天前
.NET重点
.net
m0_663234011 天前
在 .NET 5.0 运行 .NET 8.0 教程:使用 ASP.NET Core 创建 Web API
前端·asp.net·.net
小码编匠2 天前
.NET 下 RabbitMQ 队列、死信队列、延时队列及小应用
后端·c#·.net
真想骂*2 天前
vmime.net_4.dll详解:它是什么,有何用途?
.net