基于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);
      }
  }

四、实现演示

五、源码工具获取

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

相关推荐
码观天工2 小时前
AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
ai·.net·milvus·ml.net
白杨攻城狮4 小时前
.net 与 Pythonnet库的使用心得
python·c#·.net
喵叔哟4 小时前
10. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Ocelot 网关--认证
微服务·架构·.net
专注VB编程开发20年4 小时前
VB.NET 如何指定Microsoft Print To PDF的输出路径
microsoft·pdf·.net
h201701068717 小时前
C#中的委托是什么?事件是不是一种委托?委托与事件的区别?
开发语言·c#·.net·面试题
白白白白纸呀19 小时前
.NET高级应用---自定义Ioc容器(附带源码)
开发语言·c#·.net
SchuylerEX1 天前
第三章 组件(12)- 自定义组件类库
前端·c#·.net·blazor·razor·ui框架
追逐时光者1 天前
全面的C#/.NET/.NET Core面试宝典(永久免费)
后端·c#·.net
PfCoder2 天前
C# 程序结构
开发语言·c#·.net
小乖兽技术2 天前
验证测试 .NET 10 预览版的 Windows 窗体中的剪贴板新增功能
windows·.net