.NET 一維、二維碼生成DEMO

條碼技術越來越流行,已經不再侷限於物流、超市等專業行業了,很多網站都已經加上了二維碼,作爲代碼民工們,怎麼能不懂得用這門技術呢。

 

在網上找了一些資料,一維碼生成的源碼相對較多,也可用,二維碼的也不少,但我發現找來找去都是同一個DEMO,而且跑不動,暈死,後來找到了QrCodeNet的源碼才搞掂。

 

關鍵代碼如下:

一維碼生成(調用BarcodeLib):

        //生成一維碼圖片
        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):

    /// <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";
        }
    }


二維碼生成調用:

            string content = string.IsNullOrEmpty(textBox1.Text.Trim()) ? "http://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;
            }


 

DEMO已經上傳,有興趣的可以下載看一下。

DEMO開發環境:VS2012

下載地址:一維、二維碼生成DEMO

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章