基于C#實現(xiàn)簡單的二維碼和條形碼的生成工具
更新時間:2023年12月27日 08:25:53 作者:SongYuLong的博客
這篇文章主要為大家詳細介紹了如何基于C#實現(xiàn)簡單的二維碼和條形碼工具,用于二維碼條形碼的生成與識別,感興趣的小伙伴可以跟隨小編一起學習一下
C# 二維碼條形碼工具
該工具簡單實現(xiàn)了二維碼條形碼生成與識別功能,識別方式:通過攝像頭實時識別或通過圖片文件識別。
示例代碼
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) { //獲取參數(shù) 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位數(shù)字,不能有字母 barCodeWriter.Format = BarcodeFormat.EAN_13; } else if (cmboxBarCodeFormat.Text == "EAN_8") { // 輸入信息必須是7位數(shù)字,不能有字母 barCodeWriter.Format = BarcodeFormat.EAN_8; } else if (cmboxBarCodeFormat.Text == "UPC_A") { // 輸入信息必須是11位數(shù)字,不能有字母 barCodeWriter.Format = BarcodeFormat.UPC_A; } else if (cmboxBarCodeFormat.Text == "UPC_E") { // 輸入信息必須是7位數(shù)字,不能有字母,且第一位只能是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格式,否則后面無法創(chuàng)建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位數(shù)字,不能有字母 richTextBox1.Text = "輸入信息必須是12位數(shù)字,不能有字母"; } else if (cmboxBarCodeFormat.Text == "EAN_8") { // 輸入信息必須是7位數(shù)字,不能有字母 richTextBox1.Text = "輸入信息必須是7位數(shù)字,不能有字母"; } else if (cmboxBarCodeFormat.Text == "UPC_A") { // 輸入信息必須是11位數(shù)字,不能有字母 richTextBox1.Text = "輸入信息必須是11位數(shù)字,不能有字母"; } else if (cmboxBarCodeFormat.Text == "UPC_E") { // 輸入信息必須是7位數(shù)字,不能有字母,且第一位只能是0或1 richTextBox1.Text = "輸入信息必須是7位數(shù)字,不能有字母,且第一位只能是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#實現(xiàn)簡單的二維碼和條形碼的生成工具的文章就介紹到這了,更多相關C#二維碼條形碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#數(shù)據(jù)類型實現(xiàn)背包、隊列和棧
本文詳細講解了C#數(shù)據(jù)結構類型,并實現(xiàn)背包、隊列和棧的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04c#中WinForm使用OpencvSharp4實現(xiàn)簡易抓邊
本文主要介紹了c#中WinForm使用OpencvSharp4實現(xiàn)簡易抓邊,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05c#中的浮點型轉整形的舍取 四舍五入和銀行家舍入實現(xiàn)代碼
c#中的浮點型轉整形的舍取 四舍五入和銀行家舍入實現(xiàn)代碼,學習c#的朋友可以參考下2012-03-03C#/VB.NET實現(xiàn)PPT或PPTX轉換為圖像功能
由于大多數(shù)便攜式設備支持瀏覽圖片而不支持瀏覽PowerPoint 文件,所以相比較而言,圖像對于用戶而言更加友好。本文將利用C#/VB.NET實現(xiàn)PPT或PPTX轉換為圖像功能,需要的可以參考一下2022-08-08