• 多种方式C#实现生成(条码/二维码)


    C#通过第三方组件生成二维码(QR Code)和条形码(Bar Code)

    用C#如何生成二维码,我们可以通过现有的第三方dll直接来实现,下面列出几种不同的生成方法:

    1):通过QrCodeNet(Gma.QrCodeNet.Encoding.dll)来实现

    1.1):首先通过VS2015的NuGet下载对应的第三方组件,如下图所示:

     1.2):具体生成二维码方法如下

    复制代码
            private void GenerateQRByQrCodeNet()
            {
                QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                QrCode qrCode = new QrCode();
                qrEncoder.TryEncode("Hello World. This is Eric Sun Testing...", out qrCode);
    
                GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
    
                using (MemoryStream ms = new MemoryStream())
                {
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
                    Image img = Image.FromStream(ms);
                    img.Save("E:/csharp-qrcode-net.png");
                }
            }
    复制代码

    更多详细信息请参考如下链接:

    http://www.cnblogs.com/Soar1991/archive/2012/03/30/2426115.html

    http://qrcodenet.codeplex.com/ 

    http://stackoverflow.com/questions/7020136/free-c-sharp-qr-code-generator

    2):通过ThoughtWorks.QRCode(ThoughtWorks.QRCode.dll)来实现

    1.1):首先通过VS2015的NuGet下载对应的第三方组件,如下图所示:

     1.2):具体生成二维码方法如下

    复制代码
            private void GenerateQRByThoughtWorks()
            {
                QRCodeEncoder encoder = new QRCodeEncoder();
                encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;//编码方式(注意:BYTE能支持中文,ALPHA_NUMERIC扫描出来的都是数字)
                encoder.QRCodeScale = 4;//大小(值越大生成的二维码图片像素越高)
                encoder.QRCodeVersion = 0;//版本(注意:设置为0主要是防止编码的字符串太长时发生错误)
                encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;//错误效验、错误更正(有4个等级)
                encoder.QRCodeBackgroundColor = Color.Yellow;
                encoder.QRCodeForegroundColor = Color.Green;
                string qrdata = "Hello 世界! This is Eric Sun Testing....";
    
                Bitmap bcodeBitmap = encoder.Encode(qrdata.ToString());
                bcodeBitmap.Save(@"E:HelloWorld.png", ImageFormat.Png);
                bcodeBitmap.Dispose();
            }
    复制代码

    3):通过Spire.BarCode(Spire.BarCode.dll)来实现

     1.1):首先通过VS2015的NuGet下载对应的第三方组件,如下图所示:

     1.2):具体生成二维码方法如下

    复制代码
            private void GenerateQRBySpire()
            {
                BarcodeSettings bs = new BarcodeSettings()
                {
                    Data = "This is qr code: H2AMK-Z3V69-RTJZD-C7JAU-WILL4",
                    Type = BarCodeType.QRCode,
                    TopTextColor = Color.Red,
                    ShowCheckSumChar = false,
                    ShowText = false
                };
                //Generate the barcode based on the this.barCodeControl1
                BarCodeGenerator generator = new BarCodeGenerator(bs);
                Image barcode = generator.GenerateImage();
    
                //save the barcode as an image
                barcode.Save(@"E:arcode-2d.png");
            }
    复制代码

    1.3):附加具体生成条形码方法如下

    复制代码
            private void GenerateBarCodeBySpire()
            {
                BarcodeSettings bs = new BarcodeSettings()
                {
                    Data = "This is barcode: H2AMK-Z3V69-RTJZD-C7JAU-WILL4",
                    ShowCheckSumChar = false,
                    TopTextColor = Color.Red,
                    ShowTopText = false,
                    ShowTextOnBottom = true
                };
                //Generate the barcode based on the this.barCodeControl1
                BarCodeGenerator generator = new BarCodeGenerator(bs);
                Image barcode = generator.GenerateImage();
    
                //save the barcode as an image
                barcode.Save(@"E:arcode.png");
            }
    复制代码

    1.3):上诉代码我们发现生成的条形码和二维码带有水印[E-ICEBLUE],如何去除水印呢?请看如下代码

          BarcodeSettings.ApplyKey("......");

    请发送邮件到 sales@e-iceblue.com 免费获取对应的 key 值

    更多详细信息请参考如下链接:

    http://freebarcode.codeplex.com/

    http://www.e-iceblue.com/Knowledgebase/Spire.BarCode/Program-Guide/Programme-Guide-for-Spire.BarCode.html

    http://blog.csdn.net/eiceblue/article/details/43405173

    4):通过Barcode Rendering Framework(Zen.Barcode.Rendering.Framework.dll)来实现

    4.1):首先通过VS2015的NuGet下载对应的第三方组件,如下图所示:

    4.2):具体生成二维码方法如下

            private void GenerateBarCodeByZen()
            {
                Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
                Image img = barcode128.Draw("Hello World", 40);
                img.Save("E:/zenbarcode.gif");
            }

    4.3):附加具体生成条形码方法如下

            private void GenerateQRByZen()
            {
                CodeQrBarcodeDraw qrcode = BarcodeDrawFactory.CodeQr;
                Image img = qrcode.Draw("Hello World!", qrcode.GetDefaultMetrics(40));
                img.Save("E:/zenqrcode.gif");
            }

    更多详细信息请参考如下链接:

    http://barcoderender.codeplex.com/ 

    5):通过BarcodeLib(BarcodeLib.Barcode.ASP.NET.dll)来实现,下载对应dll的连接为 http://www.barcodelib.com/asp_net/

    5.1):具体生成二维码方法如下

    复制代码
            private void GenerateQRByBarcodeLib()
            {
                QRCode qrbarcode = new QRCode();
                qrbarcode.Encoding = QRCodeEncoding.Auto;
                qrbarcode.Data = "336699885522 This is Eric Sun Testing.";
    
                qrbarcode.ModuleSize = 10;
                qrbarcode.LeftMargin = 8;
                qrbarcode.RightMargin = 8;
                qrbarcode.TopMargin = 8;
                qrbarcode.BottomMargin = 8;
                qrbarcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Gif;
    
                // Save QR Code barcode image into your system
                qrbarcode.drawBarcode("E:/csharp-qrcode-lib.gif");
            }
    复制代码

    5.2):附加具体生成条形码方法如下

    复制代码
            private void GenerateLinearByBarcodeLib()
            {
                Linear barcode = new Linear();
                barcode.Type = BarcodeType.CODE128;
                barcode.Data = "CODE128";
                // other barcode settings.
    
                // save barcode image into your system
                barcode.drawBarcode("E:/barcode.png");
            }
    复制代码

    我们使用的是试用版(带水印的......),还有付费的正版,详情请参考如下链接:

    http://www.barcodelib.com/asp_net/ 

    出处:https://www.cnblogs.com/mingmingruyuedlut/p/6120671.html

    =======================================================================================

    Net Core 生成二维码 一维码

    二维码包QRCoder

    生成二维码帮助类

        public interface IQRCodeMoons: ISingletonDependency
        {
            Bitmap GetQRCode(string data, int pixel);
    
            byte[] GetQrCodeByteArray(string data, int pixel = 4);
        }
    复制代码
        /// <summary>
        /// 二维码
        /// </summary>
        public class QRCodeMoons: IQRCodeMoons
        {
            /// <summary>
            /// 生成二维码
            /// </summary>
            /// <param name="url">存储内容</param>
            /// <param name="pixel">像素大小</param>
            /// <returns></returns>
            public Bitmap GetQRCode(string data, int pixel)
            {
                QRCodeGenerator generator = new QRCodeGenerator();
                QRCodeData codeData = generator.CreateQrCode(data, QRCodeGenerator.ECCLevel.M, true);
                QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData);
                Bitmap qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, true);
                return qrImage;
            }
    
            /// <summary>
            /// 生成二维码并转成字节
            /// </summary>
            /// <param name="data"></param>
            /// <param name="pixel"></param>
            /// <returns></returns>
            public byte[] GetQrCodeByteArray(string data, int pixel = 4)
            {
                var bitmap = GetQRCode(data, pixel);
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap.Save(ms, ImageFormat.Jpeg);
                    return ms.GetBuffer();
                }
            }
        }
    复制代码

    直接把byte[] 字节返回给前端       前端通过img标签加载二维码<img "data:;base64,"+二维码字节数组 />

    前端通过img标签加载字节中的图片   

    1.在angular中     直接这样通过img加载会报错       提示不安全的url       需要对这个url进行消毒  进行安全监测

      注入消毒对象

    private sanitizer: DomSanitizer

      对当前地址进行消毒     通过[src] 属性绑定的方式    不能通过src='{{}}'这种方式绑定值       如果对html本文进行绑定也需要通过bypassSecurityTrustHtml进行消毒

              this.imageByte= this.sanitizer.bypassSecurityTrustResourceUrl("data:;base64,"+result.qrCode)
    <img  *ngIf="data" [src]="imageByte" />

    2.可以通过div   设置背景图片的方式避开这个问题    但是调用js打印的时候无法加载背景图片

                <div [ngStyle]="{'background-image':'url(data:;base64,'+data.qrCode+')'}"></div>
                <img width="75px" src="data:;base64,{{data.qrCode}}" />

    一维码包BarcodeLib

    生成一维码帮助类

        public interface IBarCodeMoons : ISingletonDependency
        {
            Image GetBarCode(string data);
    
            byte[] GetBarCodeByteArray(string data);
        }
    复制代码
        /// <summary>
        /// 一维码
        /// </summary>
        public class BarCodeMoons: IBarCodeMoons
        {
            /// <summary>
            /// 生成一维码
            /// </summary>
            /// <param name="data">存储内容</param>
            /// <returns></returns>
            public Image GetBarCode(string data)
            {
                BarcodeLib.Barcode b = new BarcodeLib.Barcode();
                Image img = b.Encode(BarcodeLib.TYPE.CODE128, data, Color.Black, Color.White, 290, 120);
                return img;
            }
    
            /// <summary>
            /// 生成一维码并转成字节
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public byte[] GetBarCodeByteArray(string data)
            {
                var img = GetBarCode(data);
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, ImageFormat.Jpeg);
                    return ms.GetBuffer();
                }
            }
        }
    复制代码 

    出处:https://www.cnblogs.com/jiangchengbiao/p/11898577.html

    =======================================================================================

    C# 利用BarcodeLib.dll生成条形码(一维,zxing,QrCodeNet/dll二维码)

    首先效果:

    1:首先下载BarcodeLib.dll 下载地址 http://pan.baidu.com/share/link?shareid=2590968386&uk=2148890391&fid=1692834292 如果不存在了则自行搜索下载。

    1.BarcodeLib.dll 一维条码库支持以下条码格式

    UPC-A

    UPC-E

    UPC 2 Digit Ext.

    UPC 5 Digit Ext.

    EAN-13

    JAN-13

    EAN-8

    ITF-14

    Codabar

    PostNet

    Bookland/ISBN

    Code 11

    Code 39

    Code 39 Extended

    Code 93

    LOGMARS

    MSI

    Interleaved 2 of 5

    Standard 2 of 5

    Code 128

    Code 128-A

    Code 128-B

    Code 128-C

    Telepen

    然后项目中添加引用

    1.  
      private void button6_Click(object sender, EventArgs e)
    2.  
      {
    3.  
      System.Drawing.Image image;
    4.  
      int width = 148, height = 55;
    5.  
      string fileSavePath = AppDomain.CurrentDomain.BaseDirectory + "BarcodePattern.jpg";
    6.  
      if (File.Exists(fileSavePath))
    7.  
      File.Delete(fileSavePath);
    8.  
      GetBarcode(height, width, BarcodeLib.TYPE.CODE128, "20131025-136", out image, fileSavePath);
    9.  
       
    10.  
      pictureBox1.Image = Image.FromFile("BarcodePattern.jpg");
    11.  
      }
    12.  
      public static void GetBarcode(int height, int width, BarcodeLib.TYPE type, string code, out System.Drawing.Image image, string fileSaveUrl)
    13.  
      {
    14.  
      try
    15.  
      {
    16.  
      image = null;
    17.  
      BarcodeLib.Barcode b = new BarcodeLib.Barcode();
    18.  
      b.BackColor = System.Drawing.Color.White;//图片背景颜色
    19.  
      b.ForeColor = System.Drawing.Color.Black;//条码颜色
    20.  
      b.IncludeLabel = true;
    21.  
      b.Alignment = BarcodeLib.AlignmentPositions.LEFT;
    22.  
      b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
    23.  
      b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;//图片格式
    24.  
      System.Drawing.Font font = new System.Drawing.Font("verdana", 10f);//字体设置
    25.  
      b.LabelFont = font;
    26.  
      b.Height = height;//图片高度设置(px单位)
    27.  
      b.Width = width;//图片宽度设置(px单位)
    28.  
       
    29.  
      image = b.Encode(type, code);//生成图片
    30.  
      image.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
    31.  
       
    32.  
      }
    33.  
      catch (Exception ex)
    34.  
      {
    35.  
       
    36.  
      image = null;
    37.  
      }
    38.  
      }

    简单的写一下。详细的去 http://www.barcodelib.com/net_barcode/main.html 这里看。




    利用 zxing.dll生成条形码和二维码  下载地址http://zxingnet.codeplex.com/

    ZXing (ZebraCrossing)是一个开源的,支持多种格式的条形码图像处理库, 。使用该类库可以方便地实现二维码图像的生成和解析。

    下载zxing.dll 项目参照引用

    1.  
      {
    2.  
      MultiFormatWriter mutiWriter = new com.google.zxing.MultiFormatWriter();
    3.  
      ByteMatrix bm = mutiWriter.encode(txtMsg.Text, com.google.zxing.BarcodeFormat.QR_CODE, 300, 300);
    4.  
      Bitmap img = bm.ToBitmap();
    5.  
      pictureBox1.Image = img;
    6.  
       
    7.  
      //自动保存图片到当前目录
    8.  
      string filename = System.Environment.CurrentDirectory + "\QR" + DateTime.Now.Ticks.ToString() + ".jpg";
    9.  
      img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
    10.  
      lbshow.Text = "图片已保存到:" + filename;
    11.  
      }
    12.  
      catch (Exception ee)
    13.  
      { MessageBox.Show(ee.Message); }





    利用 QrCodeNet.dll生成条形码和二维码  下载地址http://qrcodenet.codeplex.com/

    下载QrCodeNet.dll 项目参照引用

    1.  
      private void button2_Click(object sender, EventArgs e)
    2.  
      {
    3.  
      var codeParams = CodeDescriptor.Init(ErrorCorrectionLevel.H, textBox1.Text.Trim(), QuietZoneModules.Two, 5);
    4.  
       
    5.  
      codeParams.TryEncode();
    6.  
       
    7.  
      // Render the QR code as an image
    8.  
      using (var ms = new MemoryStream())
    9.  
      {
    10.  
      codeParams.Render(ms);
    11.  
       
    12.  
      Image image = Image.FromStream(ms);
    13.  
      pictureBox1.Image = image;
    14.  
      if (image != null)
    15.  
      pictureBox1.SizeMode = image.Height > pictureBox1.Height ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.Normal;
    16.  
      }
    17.  
       
    18.  
      }
    19.  
       /// <summary>
    20.  
          /// Class containing the description of the QR code and wrapping encoding and rendering.
    21.  
          /// </summary>
    22.  
          internal class CodeDescriptor
    23.  
          {
    24.  
              public ErrorCorrectionLevel Ecl;
    25.  
              public string Content;
    26.  
              public QuietZoneModules QuietZones;
    27.  
              public int ModuleSize;
    28.  
              public BitMatrix Matrix;
    29.  
              public string ContentType;
    30.  
       
    31.  
              /// <summary>
    32.  
              /// Parse QueryString that define the QR code properties
    33.  
              /// </summary>
    34.  
              /// <param name="request">HttpRequest containing HTTP GET data</param>
    35.  
              /// <returns>A QR code descriptor object</returns>
    36.  
              public static CodeDescriptor Init(ErrorCorrectionLevel level, string content, QuietZoneModules qzModules, int moduleSize)
    37.  
              {
    38.  
                  var cp = new CodeDescriptor();
    39.  
       
    40.  
                  Error correction level
    41.  
                  cp.Ecl = level;
    42.  
                  Code content to encode
    43.  
                  cp.Content = content;
    44.  
                  Size of the quiet zone
    45.  
                  cp.QuietZones = qzModules;
    46.  
                  Module size
    47.  
                  cp.ModuleSize = moduleSize;
    48.  
                  return cp;
    49.  
              }
    50.  
       
    51.  
              /// <summary>
    52.  
              /// Encode the content with desired parameters and save the generated Matrix
    53.  
              /// </summary>
    54.  
              /// <returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
    55.  
              public bool TryEncode()
    56.  
              {
    57.  
                  var encoder = new QrEncoder(Ecl);
    58.  
                  QrCode qr;
    59.  
                  if (!encoder.TryEncode(Content, out qr))
    60.  
                      return false;
    61.  
       
    62.  
                  Matrix = qr.Matrix;
    63.  
                  return true;
    64.  
              }
    65.  
       
    66.  
              /// <summary>
    67.  
              /// Render the Matrix as a PNG image
    68.  
              /// </summary>
    69.  
              /// <param name="ms">MemoryStream to store the image bytes into</param>
    70.  
              internal void Render(MemoryStream ms)
    71.  
              {
    72.  
                  var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
    73.  
                  render.WriteToStream(Matrix, System.Drawing.Imaging.ImageFormat.Png, ms);
    74.  
                  ContentType = "image/png";
    75.  
              }
    76.  
          }

    效果:

    参考地址:

    http://www.cnblogs.com/mzlee/archive/2011/03/19/Lee_Barcode.html

    http://blog.163.com/smxp_2006/blog/static/588682542010215163803/

    http://q.cnblogs.com/q/15253/

    http://www.csharpwin.com/csharpspace/13364r9803.shtml

    http://www.2cto.com/kf/201304/203035.html

    出处:https://blog.csdn.net/kongwei521/article/details/17588825

    =======================================================================================

    C#打印标签(包括二维码和一位条码)

    主要用到第三方库ZXing.net来生成各种条码。用PrintDocument来打印。很简单也很实用。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using ZXing;
    using ZXing.Common;
    using ZXing.QrCode;


    namespace Printtest
    {
        public partial class Form1 : Form
        {
           
            public Form1()
            {
                InitializeComponent();
            }

         

            private void button1_Click(object sender, EventArgs e)
            {
                EncodingOptions encodeOption = new EncodingOptions();
                encodeOption.Height = 50; // 高度、宽度
                encodeOption.Width = 120;
                ZXing.BarcodeWriter wr = new BarcodeWriter();
                wr.Options = encodeOption;
                wr.Format = BarcodeFormat.CODE_39; //  条形码规格
                Bitmap img = wr.Write("D1234B678A"); // 生成图片
                string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\EAN_13-" + "test" + ".jpg";
                img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);


            }

            private void button2_Click(object sender, EventArgs e)
            {
                ZXing.QrCode.QrCodeEncodingOptions qrEncodeOption = new ZXing.QrCode.QrCodeEncodingOptions();
                qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式,否则读取'中文'乱码
                qrEncodeOption.Height = 30;
                qrEncodeOption.Width = 30;
                qrEncodeOption.Margin = 1; // 设置周围空白边距

                // 2.生成条形码图片并保存
                ZXing.BarcodeWriter wr = new BarcodeWriter();
                wr.Format = BarcodeFormat.DATA_MATRIX; // 二维码
                wr.Options = qrEncodeOption;
                Bitmap img = wr.Write("D1234B678A");
                string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\QR-" + "test2" + ".jpg";
                img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                pictureBox1.Load(filePath);
            }

            private void button3_Click(object sender, EventArgs e)
            {
                this.printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("Custom",220, 120);
                //PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                //printPreviewDialog.Document = printDocument1; 打印预览代码
          try
        {
            printDocument1.Print();
         }
        catch(Exception excep)
          {
             MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
     }

            private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
            {
                Bitmap img = new Bitmap(Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory + "\EAN_13-" + "test" + ".jpg"));
                e.Graphics.DrawString("A1234B678A", new Font(new FontFamily("黑体"), 11), System.Drawing.Brushes.Black, 5, 5);
                e.Graphics.DrawImage(img, 10, 30);
                //e.Graphics.DrawString("D1234B678A", new Font(new FontFamily("黑体"), 11), System.Drawing.Brushes.Black, 10, 90);
                e.Graphics.DrawImage(pictureBox1.Image, 150, 80);
            }
           
          
        }
    }

    最终效果:

    出处:https://blog.csdn.net/mycoolme5/article/details/85323407

    =======================================================================================

    C#利用ZXing.Net生成条形码和二维码

    这篇文章主要为大家详细介绍了C#利用ZXing.Net生成条形码和二维码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    本文是利用ZXing.Net在WinForm中生成条形码,二维码的小例子,仅供学习分享使用,如有不足之处,还请指正。

    什么是ZXing.Net?

    ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。而ZXing.Net是ZXing的端口之一。

    在工程中引用ZXing.Net

    在项目中,点击项目名称右键-->管理NuGet程序包,打开NuGet包管理器窗口,进行搜索下载即可,如下图所示:

    ZXing.Net关键类结构图

    包括Reader【识别图片中的条形码和二维码】) 和Writer【生成条形码和二维码到图片中】两部分,如下图所示:

    涉及知识点:

    BarcodeWriter 用于生成图片格式的条码类,通过Write函数进行输出。继承关系如上图所示。

    BarcodeFormat 枚举类型,条码格式

    QrCodeEncodingOptions 二维码设置选项,继承于EncodingOptions,主要设置宽,高,编码方式等信息。

    MultiFormatWriter 复合格式条码写码器,通过encode方法得到BitMatrix。

    BitMatrix 表示按位表示的二维矩阵数组,元素的值用true和false表示二进制中的1和0。

    示例效果图

    关键代码

    如下所示,包含一维条码,二维条码,和带logo的条码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using ZXing;
    using ZXing.Common;
    using ZXing.QrCode;
    using ZXing.QrCode.Internal;
     
    namespace DemoQrCode
    {
     /// <summary>
     /// 描述:条形码和二维码帮助类
     /// 时间:2018-02-18
     /// </summary>
     public class BarcodeHelper
     {
      /// <summary>
      /// 生成二维码
      /// </summary>
      /// <param name="text">内容</param>
      /// <param name="width">宽度</param>
      /// <param name="height">高度</param>
      /// <returns></returns>
      public static Bitmap Generate1(string text,int width,int height)
      {
       BarcodeWriter writer = new BarcodeWriter();
       writer.Format = BarcodeFormat.QR_CODE;
       QrCodeEncodingOptions options = new QrCodeEncodingOptions()
       {
        DisableECI = true,//设置内容编码
        CharacterSet = "UTF-8", //设置二维码的宽度和高度
        Width = width,
        Height = height,
        Margin = 1//设置二维码的边距,单位不是固定像素
       };
        
       writer.Options = options;
       Bitmap map = writer.Write(text);
       return map;
      }
     
      /// <summary>
      /// 生成一维条形码
      /// </summary>
      /// <param name="text">内容</param>
      /// <param name="width">宽度</param>
      /// <param name="height">高度</param>
      /// <returns></returns>
      public static Bitmap Generate2(string text,int width,int height)
      {
       BarcodeWriter writer = new BarcodeWriter();
       //使用ITF 格式,不能被现在常用的支付宝、微信扫出来
       //如果想生成可识别的可以使用 CODE_128 格式
       //writer.Format = BarcodeFormat.ITF;
       writer.Format = BarcodeFormat.CODE_39;
       EncodingOptions options = new EncodingOptions()
       {
        Width = width,
        Height = height,
        Margin = 2
       };
       writer.Options = options;
       Bitmap map = writer.Write(text);
       return map;
      }
     
      /// <summary>
      /// 生成带Logo的二维码
      /// </summary>
      /// <param name="text">内容</param>
      /// <param name="width">宽度</param>
      /// <param name="height">高度</param>
      public static Bitmap Generate3(string text, int width, int height)
      {
       //Logo 图片
       string logoPath = System.AppDomain.CurrentDomain.BaseDirectory + @"imglogo.png";
       Bitmap logo = new Bitmap(logoPath);
       //构造二维码写码器
       MultiFormatWriter writer = new MultiFormatWriter();
       Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
       hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
       hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
       //hint.Add(EncodeHintType.MARGIN, 2);//旧版本不起作用,需要手动去除白边
        
       //生成二维码
       BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, width+30, height+30, hint);
       bm = deleteWhite(bm);
       BarcodeWriter barcodeWriter = new BarcodeWriter();
       Bitmap map = barcodeWriter.Write(bm);
     
       //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
       int[] rectangle = bm.getEnclosingRectangle();
        
       //计算插入图片的大小和位置
       int middleW = Math.Min((int)(rectangle[2] / 3), logo.Width);
       int middleH = Math.Min((int)(rectangle[3] / 3), logo.Height);
       int middleL = (map.Width - middleW) / 2;
       int middleT = (map.Height - middleH) / 2;
     
       Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
       using (Graphics g = Graphics.FromImage(bmpimg))
       {
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.DrawImage(map, 0, 0,width,height);
        //白底将二维码插入图片
        g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
        g.DrawImage(logo, middleL, middleT, middleW, middleH);
       }
       return bmpimg;
      }
     
      /// <summary>
      /// 删除默认对应的空白
      /// </summary>
      /// <param name="matrix"></param>
      /// <returns></returns>
      private static BitMatrix deleteWhite(BitMatrix matrix)
      {
       int[] rec = matrix.getEnclosingRectangle();
       int resWidth = rec[2] + 1;
       int resHeight = rec[3] + 1;
     
       BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
       resMatrix.clear();
       for (int i = 0; i < resWidth; i++)
       {
        for (int j = 0; j < resHeight; j++)
        {
         if (matrix[i + rec[0], j + rec[1]])
          resMatrix[i, j]=true;
        }
       }
       return resMatrix;
      }
     }
    }
     

    关于生成条形码和二维码的方式有很多,条码的种类也有很多种,每一种都有其对应的应用领域。

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    出处:https://www.jb51.net/article/136698.htm

    =======================================================================================

    根据上面的最后一篇文章的介绍,我自己修改了下,适用于自己的项目中:

    namespace ConsoleQrCode
    {
        using System.Drawing;
        using System.Drawing.Imaging;
        using ZXing;
        using ZXing.Common;
        using ZXing.QrCode;
        using ZXing.QrCode.Internal;
    
    
        /// <summary>
        /// 描述:条形码和二维码帮助类
        /// 时间:2018-02-18
        /// </summary>
        public class BarcodeHelper
        {
            /// <summary>
            /// 生成一维条形码的数据矩阵
            /// </summary>
            /// <param name="text"></param>
            /// <param name="width"></param>
            /// <param name="height"></param>
            /// <returns></returns>
            public static BitMatrix GenerateBitMatrix(string text, int width, int height)
            {
    
                BarcodeWriter writer = new BarcodeWriter();
                //使用ITF 格式,不能被现在常用的支付宝、微信扫出来
                //如果想生成可识别的可以使用 CODE_128 格式
                //writer.Format = BarcodeFormat.ITF;
                writer.Format = BarcodeFormat.CODE_128;
                writer.Format = BarcodeFormat.QR_CODE;
                EncodingOptions options = new EncodingOptions()
                {
                    Width = 20,
                    Height = 10,
                    GS1Format = false,
                    PureBarcode = false,
                    Margin = 0
                };
                writer.Options = options;
    
                BitMatrix bm = writer.Encode(text);
                //bm = deleteWhite(bm);
                return bm;
            }
    
            /// <summary>
            /// 生成一维条形码
            /// </summary>
            /// <param name="text">内容</param>
            /// <param name="width">宽度</param>
            /// <param name="height">高度</param>
            /// <returns></returns>
            public static Bitmap GenerateBarCode(string text, int width, int height)
            {
                BarcodeWriter writer = new BarcodeWriter();
                //使用ITF 格式,不能被现在常用的支付宝、微信扫出来
                //如果想生成可识别的可以使用 CODE_128 格式
                //writer.Format = BarcodeFormat.ITF;
                writer.Format = BarcodeFormat.CODE_128;
                EncodingOptions options = new EncodingOptions()
                {
                    Width = width,
                    Height = height,
                    //GS1Format = false,
                    //PureBarcode = true,
                    Margin = 2
                };
                writer.Options = options;
    
                BitMatrix bm = writer.Encode(text);
                //Bitmap b = writer.Write(bm);
                Bitmap b = writer.Write(text);
                return b;
            }
    
    
            /// <summary>
            /// 生成二维码
            /// </summary>
            /// <param name="text">内容</param>
            /// <param name="width">宽度</param>
            /// <param name="height">高度</param>
            /// <returns></returns>
            public static Bitmap GenerateQrCode(string text, int width, int height)
            {
                BarcodeWriter writer = new BarcodeWriter();
                writer.Format = BarcodeFormat.QR_CODE;
                QrCodeEncodingOptions options = new QrCodeEncodingOptions()
                {
                    DisableECI = true,//设置内容编码
                    CharacterSet = "UTF-8", //设置二维码的宽度和高度
                    Width = width,
                    Height = height,
                    Margin = 1//设置二维码的边距,单位不是固定像素
                };
    
                writer.Options = options;
                Bitmap map = writer.Write(text);
                return map;
            }
    
    
            /// <summary>
            /// 生成带Logo的二维码
            /// </summary>
            /// <param name="text">内容</param>
            /// <param name="width">宽度</param>
            /// <param name="height">高度</param>
            public static Bitmap GenerateQrCodeForLogo(string text, int width, int height)
            {
                //Logo 图片
                string logoPath = System.AppDomain.CurrentDomain.BaseDirectory + @"logo.jpg";
                Bitmap logo = new Bitmap(logoPath);
                //构造二维码写码器
                MultiFormatWriter writer = new MultiFormatWriter();
                Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
                hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                //hint.Add(EncodeHintType.MARGIN, 2);//旧版本不起作用,需要手动去除白边
    
                //生成二维码 
                BitMatrix bm = writer.encode(text, BarcodeFormat.QR_CODE, width + 30, height + 30, hint);
                bm = deleteWhite(bm);
                BarcodeWriter barcodeWriter = new BarcodeWriter();
                Bitmap map = barcodeWriter.Write(bm);
    
                //获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
                int[] rectangle = bm.getEnclosingRectangle();
    
                //计算插入图片的大小和位置
                int middleW = Math.Min((int)(rectangle[2] / 3), logo.Width);
                int middleH = Math.Min((int)(rectangle[3] / 3), logo.Height);
                int middleL = (map.Width - middleW) / 2;
                int middleT = (map.Height - middleH) / 2;
    
                Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(bmpimg))
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.DrawImage(map, 0, 0, width, height);
                    //白底将二维码插入图片
                    g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
                    g.DrawImage(logo, middleL, middleT, middleW, middleH);
                }
                return bmpimg;
            }
    
    
            /// <summary>
            /// 删除默认对应的空白
            /// </summary>
            /// <param name="matrix"></param>
            /// <returns></returns>
            private static BitMatrix deleteWhite(BitMatrix matrix)
            {
                int[] rec = matrix.getEnclosingRectangle();
                int resWidth = rec[2] + 1;
                int resHeight = rec[3] + 1;
    
                BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
                resMatrix.clear();
                for (int i = 0; i < resWidth; i++)
                {
                    for (int j = 0; j < resHeight; j++)
                    {
                        if (matrix[i + rec[0], j + rec[1]])
                            resMatrix[i, j] = true;
                    }
                }
                return resMatrix;
            }
    
        }
    }

    调用方式:

            static void Main(string[] args)
            {
                Console.WriteLine(@"Type some text to QR code: ");
                string sampleText = Console.ReadLine();
                sampleText = "MU8888 0731ANGB080";
                DateTime dt = DateTime.Now;
                BarcodeHelper.GenerateBarCode(sampleText, 90, 50).Save("ZXing.Net" + dt.ToString("HHmmss-fff") + "_BarCode.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                BarcodeHelper.GenerateQrCode(sampleText, 200, 200).Save("ZXing.Net" + dt.ToString("HHmmss-fff") + "_QrCode.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //BarcodeHelper.GenerateQrCodeForLogo(sampleText, 200, 200).Save("ZXing.Net" + DateTime.Now.ToString("HHmmss-fff") + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                ZXing.Common.BitMatrix bm = BarcodeHelper.GenerateBitMatrix(sampleText, 1, 1);
                Console.WriteLine();
                Console.WriteLine();
    
                Console.BackgroundColor = ConsoleColor.White;
                for (int i = 0; i < qrCode.Matrix.Width + 2; i++) Console.Write(" ");//中文全角的空格符
                Console.WriteLine();
                for (int j = 0; j < bm.Height; j++)
                {
                    for (int i = 0; i < bm.Width; i++)
                    {
                        //char charToPoint = qrCode.Matrix[i, j] ? '█' : ' ';
                        Console.Write(i == 0 ? " " : "");//中文全角的空格符
                        Console.BackgroundColor = bm[i, j] ? ConsoleColor.Black : ConsoleColor.White;
                        Console.Write(' ');//中文全角的空格符
                        Console.BackgroundColor = ConsoleColor.White;
                        Console.Write(i == bm.Width - 1 ? " " : "");//中文全角的空格符
                        //Console.Write("");
                    }
                    Console.WriteLine();
                }
                for (int i = 0; i < qrCode.Matrix.Width + 2; i++) Console.Write(" ");//中文全角的空格符
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine(@"Press any key to quit.");
    
                Console.ReadKey();
            }

    =======================================================================================

    .Net Core上也可以使用的二维码组件

    我Fork了QRCoder,并且兼容了.Net Core,图形库用的是ZKWeb.System.Drawing

    Github: https://github.com/zkweb-framework/QRCoder
    Nuget: https://www.nuget.org/packages/ZKWeb.Fork.QRCoder
    使用方法请参考原github上的文档:https://github.com/codebude/QRCoder

    出处:https://www.cnblogs.com/zkweb/p/6163506.html

    =======================================================================================

    您的资助是我最大的动力!
    金额随意,欢迎来赏!
    款后有任何问题请给我留言。

    如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
    如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我。(●'◡'●)

    如果你觉得本篇文章对你有所帮助,请给予我更多的鼓励,求打             付款后有任何问题请给我留言!!!

    因为,我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【Jack_孟】!

  • 相关阅读:
    测试用例(等价类和边界值方法)
    缺陷报告的组成
    软件测试QA、QC、QM的关系与区别
    软件的开发模式
    软件工程及生命周期
    互联网产品类型与产品工具
    canvas 时钟
    test2
    test121212
    关于iOS和OS X废弃的API你需要知道的一切
  • 原文地址:https://www.cnblogs.com/mq0036/p/14445834.html
Copyright © 2020-2023  润新知