基于C#实现简单的二维码和条形码的生成工具
作者: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#二维码条形码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!