欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET 一维、二维码生成DEMO

程序员文章站 2022-04-14 10:59:40
条码技术越来越流行,已经不再局限于物流、超市等专业行业了,很多网站都已经加上了二维码,作为代码民工们,怎么能不懂得用这门技术呢。   在网上找了一些资料,一维码生成的...

条码技术越来越流行,已经不再局限于物流、超市等专业行业了,很多网站都已经加上了二维码,作为代码民工们,怎么能不懂得用这门技术呢。

 

在网上找了一些资料,一维码生成的源码相对较多,也可用,二维码的也不少,但我发现找来找去都是同一个DEMO,而且跑不动,晕死,后来找到了QrCodeNet的源码才搞掂。

 

关键代码如下:

一维码生成(调用BarcodeLib):

[csharp]
//生成一维码图片  
private byte[] GetBarcode(int height, int width, BarcodeLib.TYPE type, 
                                   string code, out System.Drawing.Image image) 

    image = null; 
    BarcodeLib.Barcode b = new BarcodeLib.Barcode(); 
    b.BackColor = System.Drawing.Color.White; 
    b.ForeColor = System.Drawing.Color.Black; 
    b.IncludeLabel = true; 
    b.Alignment = BarcodeLib.AlignmentPositions.CENTER; 
    b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER; 
    b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; 
    System.Drawing.Font font = new System.Drawing.Font("verdana", 10f); 
    b.LabelFont = font; 
 
    b.Height = height; 
    b.Width = width; 
 
    try 
    { 
        image = b.Encode(type, code); 
    } 
    catch (Exception e) 
    { 
        MessageBox.Show(e.Message); 
        image = null; 
    } 
    //SaveImage(image, Guid.NewGuid().ToString("N") + ".png");  
    byte[] buffer = b.GetImageData(BarcodeLib.SaveTypes.GIF); 
    return buffer; 

 
//调用  
private void BuildBarcode() 

    string number = string.IsNullOrEmpty(textBox1.Text.Trim()) ? "Avx-(13614)-vR" : textBox1.Text.Trim(); 
    BarcodeLib.TYPE codeType = comboBox1.SelectedIndex == -1 ? BarcodeLib.TYPE.CODE128 : (BarcodeLib.TYPE)Enum.Parse(typeof(BarcodeLib.TYPE), comboBox1.Text); 
    System.Drawing.Image image; 
    int width = 250, height = 100; 
    byte[] buffer = GetBarcode(height, width, 
        codeType, number, out image); 
 
    pictureBox1.Image = image; 
    if (image != null) 
        pictureBox1.SizeMode = image.Height > pictureBox1.Height ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.Normal; 
}     

        //生成一维码图片
        private byte[] GetBarcode(int height, int width, BarcodeLib.TYPE type,
                                           string code, out System.Drawing.Image image)
        {
            image = null;
            BarcodeLib.Barcode b = new BarcodeLib.Barcode();
            b.BackColor = System.Drawing.Color.White;
            b.ForeColor = System.Drawing.Color.Black;
            b.IncludeLabel = true;
            b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
            b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
            b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
            System.Drawing.Font font = new System.Drawing.Font("verdana", 10f);
            b.LabelFont = font;

            b.Height = height;
            b.Width = width;

            try
            {
                image = b.Encode(type, code);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                image = null;
            }
            //SaveImage(image, Guid.NewGuid().ToString("N") + ".png");
            byte[] buffer = b.GetImageData(BarcodeLib.SaveTypes.GIF);
            return buffer;
        }

        //调用
        private void BuildBarcode()
        {
            string number = string.IsNullOrEmpty(textBox1.Text.Trim()) ? "Avx-(13614)-vR" : textBox1.Text.Trim();
            BarcodeLib.TYPE codeType = comboBox1.SelectedIndex == -1 ? BarcodeLib.TYPE.CODE128 : (BarcodeLib.TYPE)Enum.Parse(typeof(BarcodeLib.TYPE), comboBox1.Text);
            System.Drawing.Image image;
            int width = 250, height = 100;
            byte[] buffer = GetBarcode(height, width,
                codeType, number, out image);

            pictureBox1.Image = image;
            if (image != null)
                pictureBox1.SizeMode = image.Height > pictureBox1.Height ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.Normal;
        }    


二维码生成类(调用QrCodeNet):

[csharp]
/// <summary>  
/// Class containing the description of the QR code and wrapping encoding and rendering.  
/// </summary>  
internal class CodeDescriptor 

    public ErrorCorrectionLevel Ecl; 
    public string Content; 
    public QuietZoneModules QuietZones; 
    public int ModuleSize; 
    public BitMatrix Matrix; 
    public string ContentType; 
 
    /// <summary>  
    /// Parse QueryString that define the QR code properties  
    /// </summary>  
    /// <param name="request">HttpRequest containing HTTP GET data</param>  
    /// <returns>A QR code descriptor object</returns>  
    public static CodeDescriptor Init(ErrorCorrectionLevel level, string content, QuietZoneModules qzModules, int moduleSize) 
    { 
        var cp = new CodeDescriptor(); 
 
        //// Error correction level  
        cp.Ecl = level; 
        //// Code content to encode  
        cp.Content = content; 
        //// Size of the quiet zone  
        cp.QuietZones = qzModules; 
        //// Module size  
        cp.ModuleSize = moduleSize; 
        return cp; 
    } 
 
    /// <summary>  
    /// Encode the content with desired parameters and save the generated Matrix  
    /// </summary>  
    /// <returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>  
    public bool TryEncode() 
    { 
        var encoder = new QrEncoder(Ecl); 
        QrCode qr; 
        if (!encoder.TryEncode(Content, out qr)) 
            return false; 
 
        Matrix = qr.Matrix; 
        return true; 
    } 
 
    /// <summary>  
    /// Render the Matrix as a PNG image  
    /// </summary>  
    /// <param name="ms">MemoryStream to store the image bytes into</param>  
    internal void Render(MemoryStream ms) 
    { 
        var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones)); 
        render.WriteToStream(Matrix, System.Drawing.Imaging.ImageFormat.Png, ms); 
        ContentType = "image/png"; 
    } 

    /// <summary>
    /// Class containing the description of the QR code and wrapping encoding and rendering.
    /// </summary>
    internal class CodeDescriptor
    {
        public ErrorCorrectionLevel Ecl;
        public string Content;
        public QuietZoneModules QuietZones;
        public int ModuleSize;
        public BitMatrix Matrix;
        public string ContentType;

        /// <summary>
        /// Parse QueryString that define the QR code properties
        /// </summary>
        /// <param name="request">HttpRequest containing HTTP GET data</param>
        /// <returns>A QR code descriptor object</returns>
        public static CodeDescriptor Init(ErrorCorrectionLevel level, string content, QuietZoneModules qzModules, int moduleSize)
        {
            var cp = new CodeDescriptor();

            //// Error correction level
            cp.Ecl = level;
            //// Code content to encode
            cp.Content = content;
            //// Size of the quiet zone
            cp.QuietZones = qzModules;
            //// Module size
            cp.ModuleSize = moduleSize;
            return cp;
        }

        /// <summary>
        /// Encode the content with desired parameters and save the generated Matrix
        /// </summary>
        /// <returns>True if the encoding succeeded, false if the content is empty or too large to fit in a QR code</returns>
        public bool TryEncode()
        {
            var encoder = new QrEncoder(Ecl);
            QrCode qr;
            if (!encoder.TryEncode(Content, out qr))
                return false;

            Matrix = qr.Matrix;
            return true;
        }

        /// <summary>
        /// Render the Matrix as a PNG image
        /// </summary>
        /// <param name="ms">MemoryStream to store the image bytes into</param>
        internal void Render(MemoryStream ms)
        {
            var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
            render.WriteToStream(Matrix, System.Drawing.Imaging.ImageFormat.Png, ms);
            ContentType = "image/png";
        }
    }
二维码生成调用:

[csharp]
string content = string.IsNullOrEmpty(textBox1.Text.Trim()) ? "https://www.nnbh.cn" : textBox1.Text.Trim(); 
 
var codeParams = CodeDescriptor.Init(ErrorCorrectionLevel.H, content, QuietZoneModules.Two, 5); 
 
codeParams.TryEncode(); 
 
// Render the QR code as an image  
using (var ms = new MemoryStream()) 

    codeParams.Render(ms); 
 
    Image image = Image.FromStream(ms); 
    pictureBox1.Image = image; 
    if (image != null) 
        pictureBox1.SizeMode = image.Height > pictureBox1.Height ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.Normal; 

            string content = string.IsNullOrEmpty(textBox1.Text.Trim()) ? "https://www.nnbh.cn" : textBox1.Text.Trim();

            var codeParams = CodeDescriptor.Init(ErrorCorrectionLevel.H, content, QuietZoneModules.Two, 5);

            codeParams.TryEncode();

            // Render the QR code as an image
            using (var ms = new MemoryStream())
            {
                codeParams.Render(ms);

                Image image = Image.FromStream(ms);
                pictureBox1.Image = image;
                if (image != null)
                    pictureBox1.SizeMode = image.Height > pictureBox1.Height ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.Normal;
            }