• 基于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

    image

    项目结构和界面设计

    image

    三、实现核心代码

    ZXing帮助类

     /// 
     /// ZXing.NET 二维码帮助类
     /// 
     public class ZXingHelper
     {
    
         /// 
         /// 站点二维码的目录
         /// 
         private static string QRCodeDirectory = "QRCode";
         /// 
         /// 使用zxing动态库生成二维码
         /// 
         /// 二维码内容
         /// 异常信息
         /// logo图片路径,默认为空。为空时生成的二维码不带logo
         /// 二维码图片高度,默认240 单位 pixels
         /// 二维码图片宽度,默认240 单位 pixels
         /// 二维码图片边距,默认为0
         /// 
         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;
             }
         }
    
         /// 
         /// 使用zxing动态库解析:二维码,条形码......
         /// 
         /// 二维码图像
         /// 
         public static string ParseBarCode(Bitmap image)
         {
             BarcodeReader reader = new BarcodeReader();
             Result result = reader.Decode(image);
             return result.Text;
         }
    
         /// 
         /// 使用zxing动态库生成二维码
         /// 
         /// 二维码内容
         /// logo图片路径,默认为空。为空时生成的二维码不带logo
         /// 二维码图片高度,默认240 单位 pixels
         /// 二维码图片宽度,默认240 单位 pixels
         /// 二维码图片边距,默认为0
         /// 
         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

        /// 
        /// 选择logo
        /// 
        /// 
        /// 
        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);
            }
    
        }
    

    生成二维码

      /// 
      /// 生成二维码
      /// 
      /// 
      /// 
      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);
          }
      }
    

    识别二维码

      /// 
      /// 识别二维码
      /// 
      /// 
      /// 
      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);
          }
      }
    
    

    保存二维码

      /// 
      /// 保存二维码
      /// 
      /// 
      /// 
      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);
          }
      }
    

    四、实现演示

    image

    五、源码工具获取

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

  • 相关阅读:
    剑指office--字符串
    万字带你走过数据库的这激荡的三年
    操作系统 面试第一弹
    Redis 主从搭建
    【科技与狠货】云盘变硬盘
    JAVA集合问答
    【JavaWeb】火车票管理系统 (一)
    【数模】判别分析
    Google Earth Engine APP——UI地图加载一个高程显示标签并显示高程案例
    Web APIs:事件高级--DOM事件流及DOM事件流程代码验证
  • 原文地址:https://www.cnblogs.com/wml-it/p/17761875.html