基于C#实现简单的二维码和条形码的生成工具

 更新时间:2023年12月27日 08:25:53   作者:SongYuLong的博客  
这篇文章主要为大家详细介绍了如何基于C#实现简单的二维码和条形码工具,用于二维码条形码的生成与识别,感兴趣的小伙伴可以跟随小编一起学习一下

C# 二维码条形码工具

该工具简单实现了二维码条形码生成与识别功能,识别方式:通过摄像头实时识别或通过图片文件识别。

示例代码

using AForge.Genetic;
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using ZXing;
using ZXing.Common;
using ZXing.OneD;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
using ZXing.Rendering;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace BarCodeTools
{
    public partial class FormMain : Form
    {
        private Bitmap bitmap;
        private ImageFormat imgFormat = ImageFormat.Bmp; // 保存图片格式

        private string openPath = "";   // 识别图片路径
        //private string savePath = "";   // 图片保存路径
        private string logoPath = "";   // 二维码LOGO图片路径
        //private int cameraIndex = 0;    // 选择的摄像头Index

        private Color BackgroundColor = Color.White;
        private Color ForegroundColor = Color.Black;
  
        private FilterInfoCollection videoFilter;       // 摄像头设备集合
        private VideoCaptureDevice videoCaptureDevice;  // 捕获设备源

        public FormMain()
        {
            InitializeComponent();
        }

        private static Bitmap RemoveWhiteMargin(ZXing.Common.BitMatrix bitMatrix, Bitmap bitmap)
        {
            //获取参数
            int[] rec = bitMatrix.getEnclosingRectangle();
            int left = rec[0];
            int top = rec[1];
            int width = rec[2];
            int height = rec[3];
            Bitmap newImg = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(newImg);
            //截取
            g.DrawImage(bitmap, 0, 0, new Rectangle(left, top, newImg.Width, newImg.Height), GraphicsUnit.Pixel);
            return newImg;
        }


        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <returns></returns>
        private Bitmap GenerateBarCode()
        {             
            BarcodeWriter barCodeWriter = new BarcodeWriter();
            EAN8Writer eAN8Writer = new EAN8Writer();
            EAN13Writer eAN13Writer = new EAN13Writer();
            UPCAWriter upCAWriter = new UPCAWriter();
            UPCEWriter UPCEWriter = new UPCEWriter();

            EncodingOptions options = new EncodingOptions()
            {
                Width = Convert.ToInt32(numBarCodeWidth.Value),
                Height = Convert.ToInt32(numBarCodeHeigh.Value),
                Margin = Convert.ToInt32(numBarCodeMargin.Value),
            };
                               
            barCodeWriter.Options = options;
            
            string text = textBoxBarCodeText.Text.Trim();

            if (cmboxBarCodeFormat.Text == "CODE_128")
            {
                barCodeWriter.Format = BarcodeFormat.CODE_128;
            }
            else if (cmboxBarCodeFormat.Text == "CODE_39") {
                barCodeWriter.Format = BarcodeFormat.CODE_39;
            }
            else if (cmboxBarCodeFormat.Text == "CODE_93")
            {
                barCodeWriter.Format = BarcodeFormat.CODE_93;
            }            
            else if (cmboxBarCodeFormat.Text == "EAN_13")
            {
                // 输入信息必须是12位数字,不能有字母
                barCodeWriter.Format = BarcodeFormat.EAN_13;
            }
            else if (cmboxBarCodeFormat.Text == "EAN_8")
            {
                // 输入信息必须是7位数字,不能有字母
                barCodeWriter.Format = BarcodeFormat.EAN_8;
            }
            else if (cmboxBarCodeFormat.Text == "UPC_A")
            {
                // 输入信息必须是11位数字,不能有字母
                barCodeWriter.Format = BarcodeFormat.UPC_A;
            }
            else if (cmboxBarCodeFormat.Text == "UPC_E")
            {
                // 输入信息必须是7位数字,不能有字母,且第一位只能是0或1
                barCodeWriter.Format = BarcodeFormat.UPC_E;
            }

            Bitmap map = null;
            try { 
                map = barCodeWriter.Write(text);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "条形码生成错误");
                Console.WriteLine(e.ToString());
            }
            return map;
        }


        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <returns></returns>
        private Bitmap GenerateQrCode()
        {
            BarcodeWriter barcodeWriter = new BarcodeWriter();
            barcodeWriter.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();
            options.DisableECI = false;
            options.CharacterSet = "UTF-8";
            options.Width = Convert.ToInt32(numQrCodeWidth.Value);
            options.Height = Convert.ToInt32(numQrCodeHeight.Value);
            options.Margin = Convert.ToInt32(numQrCodeMargin.Value);          
            barcodeWriter.Options = options;

            barcodeWriter.Renderer = new BitmapRenderer
            {
                Background = BackgroundColor, //Color.White,
                Foreground = ForegroundColor  //Color.Black
            };

            Bitmap map = null;
            try
            {
                string text = richTextBoxQrCode.Text.Trim();
                map = barcodeWriter.Write(text);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "二维码生成错误", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }          

            return map;
        }


        private Bitmap GenerateQrCodeWithLogo()
        {
            Bitmap bmpimg = null; // 最终生成的二维码图片

            // 载入Logo图片
            Bitmap logo = new Bitmap(logoPath);

            // 构造二维码写码器
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            // 生成二维码
            string text = richTextBoxQrCode.Text.Trim();
            Int32 width = Convert.ToInt32(numQrCodeWidth.Value);
            Int32 height = Convert.ToInt32(numQrCodeHeight.Value);
            BitMatrix bm = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hint);
            BarcodeWriter barcodeWriter = new BarcodeWriter();            
            barcodeWriter.Renderer = new BitmapRenderer
            {
                Background = BackgroundColor, //Color.White,
                Foreground = ForegroundColor //Color.Black
            };
            Bitmap qrcode_map = barcodeWriter.Write(bm);


            // h获取二维码实际尺寸(去掉二维码两边空白后的尺寸)
            int[] rectangle = bm.getEnclosingRectangle();

            // 计算LOGO图片插入的大小位置信息
            int W = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
            int H = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
            int L = (qrcode_map.Width - W) / 2;
            int T = (qrcode_map.Height - H) / 2;

#if true
            // 将img转换成bmp格式,否则后面无法创建Graphics对象
            bmpimg = new Bitmap(qrcode_map.Width, qrcode_map.Height, System.Drawing.Imaging.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(qrcode_map, 0, 0);
            }

            // 将二维码插入到图片
            Graphics mGraphics = Graphics.FromImage(bmpimg);

            // 白底
            mGraphics.FillRectangle(Brushes.White, L, T, W, H);
            mGraphics.DrawImage(logo, L, T, W, H);
#endif
            return bmpimg;
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            timer1.Interval = 200;  // 摄像头实时识别周期
        }

        //-----------------------------------生成条形码------------------------------------------------------

        private void btnBarCodeGenerate_Click(object sender, EventArgs e)
        {
            
            bitmap = GenerateBarCode();

            //bitmap.Save("");

            if (bitmap != null) { 
                pictureBoxBarCodePreView.Image = Image.FromHbitmap(bitmap.GetHbitmap());
            }

           //bitmap.Dispose();
        }

        private void btnBarCodeSave_Click(object sender, EventArgs e)
        {
            if (bitmap == null) {
                MessageBox.Show("请先生成条形码","图片保存失败");
                return;
            }

            try {
                //bitmap.Save(textBoxBarCodeSavePath.Text.Trim(), System.Drawing.Imaging.ImageFormat.Png);
                bitmap.Save(textBoxBarCodeSavePath.Text.Trim(), imgFormat);
                MessageBox.Show("图片保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("图片保存失败"+ex.ToString());
            }            
        }

        private void btnBarCodeSavePath_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "PNG Image|*.png|Bitmap Image|*.bmp";
            saveFileDialog.DefaultExt = "*.bmp";

            if (saveFileDialog.ShowDialog() == DialogResult.OK) { 
                string fName = saveFileDialog.FileName;
                textBoxBarCodeSavePath.Text = fName;

                switch (saveFileDialog.FilterIndex)
                {
                    case 0:
                        // SAVE PNG
                        imgFormat = ImageFormat.Png;
                        break;
                    case 1:
                        // SAVE BMP
                        imgFormat = ImageFormat.Bmp;
                        break;
                    default:
                        break;
                }
            }
        }

        private void cmboxBarCodeFormat_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cmboxBarCodeFormat.Text == "CODE_128")
            {
                richTextBox1.Text = "";
            }
            else if (cmboxBarCodeFormat.Text == "CODE_39")
            {
                richTextBox1.Text = "";
            }
            else if (cmboxBarCodeFormat.Text == "CODE_93")
            {
                richTextBox1.Text = "";
            }
            else if (cmboxBarCodeFormat.Text == "EAN_13")
            {
                // 输入信息必须是12位数字,不能有字母
                richTextBox1.Text = "输入信息必须是12位数字,不能有字母";
            }
            else if (cmboxBarCodeFormat.Text == "EAN_8")
            {
                // 输入信息必须是7位数字,不能有字母
                richTextBox1.Text = "输入信息必须是7位数字,不能有字母";
            }
            else if (cmboxBarCodeFormat.Text == "UPC_A")
            {
                // 输入信息必须是11位数字,不能有字母
                richTextBox1.Text = "输入信息必须是11位数字,不能有字母";
            }
            else if (cmboxBarCodeFormat.Text == "UPC_E")
            {
                // 输入信息必须是7位数字,不能有字母,且第一位只能是0或1
                richTextBox1.Text = "输入信息必须是7位数字,不能有字母,且第一位只能是0或1";

            }
        }

        //-----------------------------------生成二维码------------------------------------------------------

        /// <summary>
        ///  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQrCodeLogo_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "PNG *.png|*.png|BMP *.bmp|*.bmp|JPG *.jpg|*.jpg|all files *.*|*.*";
            openFileDialog.DefaultExt = "*.png";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            { 
                logoPath = openFileDialog.FileName;

                Bitmap bmap = new Bitmap(logoPath);
                //picBoxQrCodeLogo.Image = bmap;
                picBoxQrCodeLogo.Image = Image.FromHbitmap(bmap.GetHbitmap());
            }
        }

        private void btnGenerateQrCode_Click(object sender, EventArgs e)
        {
            if (checkBokQrCodeWithLogo.Checked && logoPath != "")
            {
                bitmap = GenerateQrCodeWithLogo();
            }
            else 
            { 
                bitmap = GenerateQrCode();            
            }

            //bitmap.Save("");

            if (bitmap != null)
            {
                picBoxQrCodePreview.Image = Image.FromHbitmap(bitmap.GetHbitmap());
            }

        }

        private void btnSaveQrCode_Click(object sender, EventArgs e)
        {
            if (bitmap == null)
            {
                MessageBox.Show("请先生成二维码", "图片保存失败");
                return;
            }

            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "PNG *.png|*.png|BMP *.bmp|*.bmp|JPG *.jpg|*.jpg|all files *.*|*.*";
                saveFileDialog.DefaultExt = "*.png";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {

                    imgFormat = ImageFormat.Bmp;

                    //bitmap.Save(textBoxBarCodeSavePath.Text.Trim(), System.Drawing.Imaging.ImageFormat.Png);
                    bitmap.Save(saveFileDialog.FileName, imgFormat);
                    MessageBox.Show("图片保存成功");
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show("图片保存失败"+ex.ToString());
            }
        }

        private void checkBokQrCodeWithLogo_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBokQrCodeWithLogo.Checked)
            {

            }
            else
            {
                picBoxQrCodeLogo.Image = null;
                logoPath = "";
            }
            
        }

        // 二维码条形码识别

        protected Result BarCodeReaderReco(Bitmap map)
        {            
            BarcodeReader reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";

            Result result = reader.Decode(map);

            if (result != null)
            {
                if (result.BarcodeFormat == BarcodeFormat.QR_CODE)
                {
                    textBoxCodeFormat.Text = "QR_CODE";
                }
                else if (result.BarcodeFormat == BarcodeFormat.CODE_128)
                {
                    textBoxCodeFormat.Text = "CODE_128";
                }
                else if (result.BarcodeFormat == BarcodeFormat.CODE_39)
                {
                    textBoxCodeFormat.Text = "CODE_39";
                }
                else if (result.BarcodeFormat == BarcodeFormat.CODE_93)
                {
                    textBoxCodeFormat.Text = "CODE_93";
                }
                else if (result.BarcodeFormat == BarcodeFormat.EAN_8)
                {
                    textBoxCodeFormat.Text = "EAN_8";
                }
                else if (result.BarcodeFormat == BarcodeFormat.EAN_13)
                {
                    textBoxCodeFormat.Text = "EAN_13";
                }
                else if (result.BarcodeFormat == BarcodeFormat.UPC_A)
                {
                    textBoxCodeFormat.Text = "UPC_A";
                }
                else if (result.BarcodeFormat == BarcodeFormat.UPC_E)
                {
                    textBoxCodeFormat.Text = "UPC_E";
                }
                else
                {
                    textBoxCodeFormat.Text = "未知编码类型";
                }

                richTextBoxReco.Text = result.Text;
            }
            else 
            {
                
            }

            return result;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "图片文件 PNG *.png|*.png|BMP *.bmp|*.bmp|JPG *.jpg|*.jpg|all files *.*|*.*";
            openFileDialog.DefaultExt = "*.png";
            if (openFileDialog.ShowDialog() == DialogResult.OK) {
                openPath = openFileDialog.FileName;

                textBoxCodeFormat.Text = "";
                richTextBoxReco.Text = "";

                Bitmap bmap = new Bitmap(openPath);
                pictureBoxReco.Image = Image.FromHbitmap(bmap.GetHbitmap());
                Result ret = BarCodeReaderReco(bmap);                
            }           
        }

        private void button3_Click(object sender, EventArgs e)
        {
            videoFilter = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            MessageBox.Show("识别到:" + videoFilter.Count.ToString() + "个摄像头");

            comboBoxVideos.Items.Clear();
            
            for (int i = 0; i < videoFilter.Count; i++)
            {
                comboBoxVideos.Items.Add(videoFilter[i].Name);
            }
            
            comboBoxVideos.SelectedIndex = 0;
        }

        private void CameraClose()
        {
            if (null != videoSourcePlayer1.VideoSource) { 
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.WaitForStop();
                videoSourcePlayer1.VideoSource = null;
            }

            timer1.Stop();
        }
        private void comboBoxVideos_SelectedIndexChanged(object sender, EventArgs e)
        {

#if false
            if (videoFilter.Count > comboBoxVideos.SelectedIndex)
            {
                cameraIndex = comboBoxVideos.SelectedIndex;
            }
            else
            {
                cameraIndex = 0;
                MessageBox.Show("选择的摄像头不存在,请刷新重新获取摄像头!");
                return;
            }
#else
            CameraClose();
            string CameraName = "";
            if (videoFilter.Count > comboBoxVideos.SelectedIndex)
            {
                CameraName = videoFilter[comboBoxVideos.SelectedIndex].MonikerString;
            }
            else {
                MessageBox.Show("选择的摄像头不存在,请刷新重新获取摄像头!");
                return;
            }

            videoCaptureDevice = new VideoCaptureDevice(CameraName);
            videoSourcePlayer1.VideoSource = videoCaptureDevice;
            videoSourcePlayer1.Start();

            timer1.Start();
#endif
        }

        private void button2_Click(object sender, EventArgs e)
        {
#if true
             CameraClose();
#else
            if (button2.Text == "打开摄像头")
            {
                CameraClose();
                string CameraName = "";
                if (videoFilter.Count > cameraIndex)
                {
                    CameraName = videoFilter[cameraIndex].MonikerString;
                }
                else
                {
                    MessageBox.Show("选择的摄像头不存在,请刷新重新获取摄像头!");
                    return;
                }

                videoCaptureDevice = new VideoCaptureDevice(CameraName);
                videoSourcePlayer1.VideoSource = videoCaptureDevice;
                videoSourcePlayer1.Start();
                  
                timer1.Start();
                button2.Text = "关闭摄像头";
            }
            else {
                CameraClose();
                button2.Text = "打开摄像头";
            }
#endif            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (videoSourcePlayer1.VideoSource != null) {
                Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame();  // 获取图片
                //pictureBoxReco.Image = bitmap;


                if (bitmap != null) {
                    Result ret = BarCodeReaderReco(bitmap);                    
                }
               
            }
        }

        private void btnQrCodeBackground_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                BackgroundColor = colorDialog.Color;
                labelQrCodeBackground.BackColor = BackgroundColor;
            }
        }

        private void btnQrCodeForeground_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                ForegroundColor = colorDialog.Color;
                labelQrCodeForeground.BackColor = ForegroundColor;
            }
        }

        private void labelQrCodeBackground_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                BackgroundColor = colorDialog.Color;
                labelQrCodeBackground.BackColor = BackgroundColor;
            }
        }

        private void labelQrCodeForeground_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if (colorDialog.ShowDialog() == DialogResult.OK)
            {
                ForegroundColor = colorDialog.Color;
                labelQrCodeForeground.BackColor = ForegroundColor;
            }
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void FormMain_Leave(object sender, EventArgs e)
        {
           
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Console.WriteLine(" App Closing to close camera.");
            CameraClose();
        }
    }
}

到此这篇关于基于C#实现简单的二维码和条形码的生成工具的文章就介绍到这了,更多相关C#二维码条形码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#实现拼手气红包算法

    C#实现拼手气红包算法

    这篇文章主要为大家详细介绍了C#实现拼手气红包算法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-09-09
  • C#字符串加密解密方法实例

    C#字符串加密解密方法实例

    这篇文章主要介绍了C#字符串加密解密方法,实例分析了C#对字符串加密与解密的操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-03-03
  • C#使用RabbitMq队列(Sample,Work,Fanout,Direct等模式的简单使用)

    C#使用RabbitMq队列(Sample,Work,Fanout,Direct等模式的简单使用)

    这篇文章主要介绍了C#使用RabbitMq队列(Sample,Work,Fanout,Direct等模式的简单使用),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • C#中Winfrom默认输入法的设置方法

    C#中Winfrom默认输入法的设置方法

    这篇文章主要介绍了C#中Winfrom默认输入法的设置方法,以实例形式较为详细的分析了C#中输入法设置的相关技巧,需要的朋友可以参考下
    2015-05-05
  • C# winForm自定义弹出页面效果

    C# winForm自定义弹出页面效果

    这篇文章主要为大家详细介绍了C# winForm自定义弹出页面效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • C#中数据类型的转换介绍

    C#中数据类型的转换介绍

    大家好,本篇文章主要讲的是C#中数据类型的转换介绍,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2022-01-01
  • C#使用System.Threading.Timer实现计时器的示例详解

    C#使用System.Threading.Timer实现计时器的示例详解

    以往一般都是用 System.Timers.Timer 来做计时器,其实 System.Threading.Timer 也可以实现计时器功能,下面就跟随小编一起来学习一下如何使用System.Threading.Timer实现计时器功能吧
    2024-01-01
  • C#基于Extension Method(扩展方法)获得文件大小的方法

    C#基于Extension Method(扩展方法)获得文件大小的方法

    这篇文章主要介绍了C#基于Extension Method(扩展方法)获得文件大小的方法,实例分析了C#扩展方法的定义与文件操作的相关技巧,需要的朋友可以参考下
    2015-06-06
  • C# SelectedIndexChanged事件详解

    C# SelectedIndexChanged事件详解

    这篇文章主要介绍了C# SelectedIndexChanged事件详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • C#中重载重写和覆盖的定义与区别

    C#中重载重写和覆盖的定义与区别

    今天小编就为大家分享一篇关于C#中重载重写和覆盖的定义与区别,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10

最新评论