C# Barcode Scanner: Read Barcodes & QR Codes in .NET Applications
需要在您的 .NET 應用程式中快速掃描 BarCode 或 QR 碼嗎? 無論您處理的是完美的數位影像,還是條件艱難的實景照片,IronBarcode 都能讓條碼讀取變得簡單且可靠。 本指南將透過可立即運用的實用範例,詳細說明如何在 C# 中實作 BarCode 掃描功能。
快速入門:立即從檔案讀取BarCode
這個簡短範例將向您展示,開始使用 IronBarcode 是多麼簡單。 只需一行程式碼,即可從影像檔案讀取BarCode——無需複雜的設定。
簡化工作流程(5 個步驟)
- 透過 NuGet 或 DLL 下載安裝 IronBarcode
- 使用
BarcodeReader.Read方法掃描任何 BARCODE 或 QR 碼 - 在單次掃描、PDF 或多幀 TIFF 檔案中讀取多個 BARCODE 或 QR 碼
- 啟用 IronBarcode 的進階濾鏡功能,解碼掃描品質不佳的條碼及照片
- 下載教學專案並立即開始掃描
如何在我的 .NET 專案中安裝 IronBarcode?
IronBarcode 可透過 NuGet 套件管理員輕鬆安裝,或直接下載 DLL 檔案。 建議採用 NuGet 安裝方式,因其能自動管理依賴項與更新。
Install-Package BarCode
安裝完成後,請在您的 C# 檔案中加入 using IronBarCode; 以存取 BARCODE 掃描功能。 如需不同開發環境的詳細安裝說明,請參閱我們的安裝指南。
如何使用 C# 讀取第一個 BARCODE?
using IronBarcode 讀取 BARCODE 只需一行程式碼。 此函式庫可自動偵測BarCode格式,並擷取所有編碼資料。
*IronBarcode 可立即讀取的標準 Code128 BARCODE*using IronBarCode;
using System;
// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");
// Check if any barcodes were detected
if (results != null && results.Co/unt > 0)
{
// Process each barcode found in the image
foreach (BarcodeResult result in results)
{
// Extract the text value from the barcode
Console.WriteLine("Barcode detected! Value: " + result.Text);
// Additional properties available:
// result.BarcodeType - The format (Code128, QR, etc.)
// result.BinaryValue - Raw binary data if applicable
// result.Co/nfidence - Detection confidence score
}
}
else
{
Console.WriteLine("No barcodes detected in the image.");
}
using IronBarCode;
using System;
// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");
// Check if any barcodes were detected
if (results != null && results.Co/unt > 0)
{
// Process each barcode found in the image
foreach (BarcodeResult result in results)
{
// Extract the text value from the barcode
Console.WriteLine("Barcode detected! Value: " + result.Text);
// Additional properties available:
// result.BarcodeType - The format (Code128, QR, etc.)
// result.BinaryValue - Raw binary data if applicable
// result.Co/nfidence - Detection confidence score
}
}
else
{
Console.WriteLine("No barcodes detected in the image.");
}
Imports IronBarCode
Imports System
' Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
Dim results As BarcodeResults = BarcodeReader.Read("GetStarted.png")
' Check if any barcodes were detected
If results IsNot Nothing AndAlso results.Count > 0 Then
' Process each barcode found in the image
For Each result As BarcodeResult In results
' Extract the text value from the barcode
Console.WriteLine("Barcode detected! Value: " & result.Text)
' Additional properties available:
' result.BarcodeType - The format (Code128, QR, etc.)
' result.BinaryValue - Raw binary data if applicable
' result.Confidence - Detection confidence score
Next
Else
Console.WriteLine("No barcodes detected in the image.")
End If
BarcodeReader.Read 方法會傳回一個 BarcodeResults 集合,其中包含所有偵測到的 BARCODE。 每個 BarcodeResult 皆可存取BARCODE的文字值、格式類型、位置座標及二進位資料。 此方案可無縫支援常見的 BARCODE 格式,包括 Code128、Code39、QR 碼及 Data Matrix 碼。
有哪些選項有助於讀取難以辨識或受損的BARCODE?
實際的BARCODE掃描情境中,常會遇到影像品質不佳的情況——例如角度歪斜、光線不足或部分損毀。 IronBarcode 的進階選項能有效應對這些挑戰。
using IronBarCode;
// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Speed settings: Faster, Balanced, Detailed, ExtremeDetail
// ExtremeDetail performs deep analysis for challenging images
Speed = ReadingSpeed.ExtremeDetail,
// Specify expected formats to improve performance
// Use bitwise OR (|) to combine multiple formats
ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Co/de128,
// Maximum number of barcodes to find (0 = unlimited)
MaxParallelThreads = 4,
// Crop region for faster processing of specific areas
CropArea = null // Or specify a Rectangle
};
// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
// Process detected barcodes
foreach (var barcode in results)
{
Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
using IronBarCode;
// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Speed settings: Faster, Balanced, Detailed, ExtremeDetail
// ExtremeDetail performs deep analysis for challenging images
Speed = ReadingSpeed.ExtremeDetail,
// Specify expected formats to improve performance
// Use bitwise OR (|) to combine multiple formats
ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Co/de128,
// Maximum number of barcodes to find (0 = unlimited)
MaxParallelThreads = 4,
// Crop region for faster processing of specific areas
CropArea = null // Or specify a Rectangle
};
// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
// Process detected barcodes
foreach (var barcode in results)
{
Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
Imports IronBarCode
' Configure advanced reading options for difficult barcodes
Dim options As New BarcodeReaderOptions With {
' Speed settings: Faster, Balanced, Detailed, ExtremeDetail
' ExtremeDetail performs deep analysis for challenging images
.Speed = ReadingSpeed.ExtremeDetail,
' Specify expected formats to improve performance
' Use bitwise OR (|) to combine multiple formats
.ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
' Maximum number of barcodes to find (0 = unlimited)
.MaxParallelThreads = 4,
' Crop region for faster processing of specific areas
.CropArea = Nothing ' Or specify a Rectangle
}
' Apply options when reading
Dim results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)
' Process detected barcodes
For Each barcode In results
Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}")
Next barcode
*IronBarcode 透過進階選項成功讀取的旋轉 QR 碼*ExpectBarcodeTypes 屬性透過將搜尋範圍限制在特定格式,顯著提升了效能。 針對難以辨識的圖片,請結合使用圖片濾鏡與自動旋轉功能以確保最高準確度:
using IronBarCode;
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Apply image processing filters to enhance readability
ImageFilters = new ImageFilterCollection
{
new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
new ContrastFilter(2.0f), // Increases contrast
new SharpenFilter() // Reduces blur
},
// Automatically rotate to find barcodes at any angle
AutoRotate = true,
// Use multiple CPU cores for faster processing
Multithreaded = true
};
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
foreach (var result in results)
{
Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
Console.WriteLine($"Confidence: {result.Co/nfidence}%");
Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
using IronBarCode;
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Apply image processing filters to enhance readability
ImageFilters = new ImageFilterCollection
{
new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
new ContrastFilter(2.0f), // Increases contrast
new SharpenFilter() // Reduces blur
},
// Automatically rotate to find barcodes at any angle
AutoRotate = true,
// Use multiple CPU cores for faster processing
Multithreaded = true
};
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
foreach (var result in results)
{
Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
Console.WriteLine($"Confidence: {result.Co/nfidence}%");
Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
Imports IronBarCode
Dim options As New BarcodeReaderOptions With {
.ImageFilters = New ImageFilterCollection From {
New AdaptiveThresholdFilter(9, 0.01F), ' Handles varying lighting
New ContrastFilter(2.0F), ' Increases contrast
New SharpenFilter() ' Reduces blur
},
.AutoRotate = True, ' Automatically rotate to find barcodes at any angle
.Multithreaded = True ' Use multiple CPU cores for faster processing
}
Dim results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)
For Each result In results
Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}")
Console.WriteLine($"Confidence: {result.Confidence}%")
Console.WriteLine($"Position: X={result.X}, Y={result.Y}")
Next
這些進階功能使 IronBarcode 成為掃描照片、監視器畫面或行動裝置擷取畫面中條碼的理想選擇,即使這些影像的畫質差異極大。
如何從 PDF 文件中掃描多個 BARCODE?
PDF BarCode掃描對於處理發票、運送標籤及庫存文件至關重要。 IronBarcode 能高效讀取每頁上的所有 BarCode。
從 PDF 檔案讀取 BarCode
using System;
using IronBarCode;
try
{
// Scan all pages of a PDF for barcodes
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
if (results != null && results.Co/unt > 0)
{
foreach (var barcode in results)
{
// Access barcode data and metadata
string value = barcode.Text;
int pageNumber = barcode.PageNumber;
BarcodeEncoding format = barcode.BarcodeType;
byte[] binaryData = barcode.BinaryValue;
// Extract barcode image if needed
System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;
Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
}
}
else
{
Console.WriteLine("No barcodes found in the PDF.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading PDF: {ex.Message}");
}
using System;
using IronBarCode;
try
{
// Scan all pages of a PDF for barcodes
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
if (results != null && results.Co/unt > 0)
{
foreach (var barcode in results)
{
// Access barcode data and metadata
string value = barcode.Text;
int pageNumber = barcode.PageNumber;
BarcodeEncoding format = barcode.BarcodeType;
byte[] binaryData = barcode.BinaryValue;
// Extract barcode image if needed
System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;
Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
}
}
else
{
Console.WriteLine("No barcodes found in the PDF.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading PDF: {ex.Message}");
}
Imports System
Imports IronBarCode
Try
' Scan all pages of a PDF for barcodes
Dim results As BarcodeResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf")
If results IsNot Nothing AndAlso results.Count > 0 Then
For Each barcode In results
' Access barcode data and metadata
Dim value As String = barcode.Text
Dim pageNumber As Integer = barcode.PageNumber
Dim format As BarcodeEncoding = barcode.BarcodeType
Dim binaryData As Byte() = barcode.BinaryValue
' Extract barcode image if needed
Dim barcodeImage As System.Drawing.Bitmap = barcode.BarcodeImage
Console.WriteLine($"Found {format} on page {pageNumber}: {value}")
Next
Else
Console.WriteLine("No barcodes found in the PDF.")
End If
Catch ex As Exception
Console.WriteLine($"Error reading PDF: {ex.Message}")
End Try
控制台輸出顯示在不同 PDF 頁面上發現了多個 BARCODE
若需處理特定頁碼範圍或進階 PDF 處理功能,請使用 BarcodeReaderOptions:
// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
// Scan pages 1-5 only
PageNumbers = new[] { 1, 2, 3, 4, 5 },
// PDF-specific settings
PdfDpi = 300, // Higher DPI for better accuracy
ReadBehindVectorGraphics = true
};
BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
// Scan pages 1-5 only
PageNumbers = new[] { 1, 2, 3, 4, 5 },
// PDF-specific settings
PdfDpi = 300, // Higher DPI for better accuracy
ReadBehindVectorGraphics = true
};
BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
' Read only specific pages to improve performance
Dim pdfOptions As New BarcodeReaderOptions With {
.PageNumbers = { 1, 2, 3, 4, 5 },
.PdfDpi = 300,
.ReadBehindVectorGraphics = True
}
Dim results As BarcodeResults = BarcodeReader.ReadPdf("document.pdf", pdfOptions)
如何處理多幀 TIFF 影像?
常見於文件掃描和傳真系統的多幀 TIFF 檔案,與 PDF 檔案一樣獲得全面支援。
一個包含多個圖層的 TIFF 檔案,各圖層上印有 BarCode
using IronBarCode;
// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");
foreach (var result in multiFrameResults)
{
// Access frame-specific information
int frameNumber = result.PageNumber; // Frame number in TIFF
string barcodeValue = result.Text;
Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");
// Save individual barcode images if needed
result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
using IronBarCode;
// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");
foreach (var result in multiFrameResults)
{
// Access frame-specific information
int frameNumber = result.PageNumber; // Frame number in TIFF
string barcodeValue = result.Text;
Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");
// Save individual barcode images if needed
result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
Imports IronBarCode
' TIFF files are processed similarly to regular images
' Each frame is scanned automatically
Private multiFrameResults As BarcodeResults = BarcodeReader.Read("Multiframe.tiff")
For Each result In multiFrameResults
' Access frame-specific information
Dim frameNumber As Integer = result.PageNumber ' Frame number in TIFF
Dim barcodeValue As String = result.Text
Console.WriteLine($"Frame {frameNumber}: {barcodeValue}")
' Save individual barcode images if needed
If result.BarcodeImage IsNot Nothing Then
result.BarcodeImage.Save($"barcode_frame_{frameNumber}.png")
End If
Next result
針對 TIFF 處理(包括影像濾鏡與旋轉設定),同樣適用 BarcodeReaderOptions 規範。 有關 TIFF 處理的詳細情境,請參閱我們的影像處理教學指南。
我能否透過多執行緒來加快處理速度?
處理多份文件時,平行處理能帶來顯著效益。 IronBarcode 會自動利用可用的 CPU 核心以達到最佳效能。
using IronBarCode;
// List of documents to process - mix of formats supported
var documentBatch = new[]
{
"invoice1.pdf",
"shipping_label.png",
"inventory_sheet.tiff",
"product_catalog.pdf"
};
// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
// Enable parallel processing across documents
Multithreaded = true,
// Limit threads if needed (0 = use all cores)
MaxParallelThreads = Environment.ProcessorCount,
// Apply consistent settings to all documents
Speed = ReadingSpeed.Balanced,
ExpectBarcodeTypes = BarcodeEncoding.All
};
// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);
// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);
foreach (var docGroup in resultsByDocument)
{
Console.WriteLine($"\nDocument: {docGroup.Key}");
foreach (var barcode in docGroup)
{
Console.WriteLine($" - {barcode.BarcodeType}: {barcode.Text}");
}
}
using IronBarCode;
// List of documents to process - mix of formats supported
var documentBatch = new[]
{
"invoice1.pdf",
"shipping_label.png",
"inventory_sheet.tiff",
"product_catalog.pdf"
};
// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
// Enable parallel processing across documents
Multithreaded = true,
// Limit threads if needed (0 = use all cores)
MaxParallelThreads = Environment.ProcessorCount,
// Apply consistent settings to all documents
Speed = ReadingSpeed.Balanced,
ExpectBarcodeTypes = BarcodeEncoding.All
};
// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);
// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);
foreach (var docGroup in resultsByDocument)
{
Console.WriteLine($"\nDocument: {docGroup.Key}");
foreach (var barcode in docGroup)
{
Console.WriteLine($" - {barcode.BarcodeType}: {barcode.Text}");
}
}
Imports Microsoft.VisualBasic
Imports IronBarCode
' List of documents to process - mix of formats supported
Private documentBatch = { "invoice1.pdf", "shipping_label.png", "inventory_sheet.tiff", "product_catalog.pdf" }
' Configure for batch processing
Private batchOptions As New BarcodeReaderOptions With {
.Multithreaded = True,
.MaxParallelThreads = Environment.ProcessorCount,
.Speed = ReadingSpeed.Balanced,
.ExpectBarcodeTypes = BarcodeEncoding.All
}
' Process all documents in parallel
Private batchResults As BarcodeResults = BarcodeReader.Read(documentBatch, batchOptions)
' Group results by source document
Private resultsByDocument = batchResults.GroupBy(Function(r) r.Filename)
For Each docGroup In resultsByDocument
Console.WriteLine($vbLf & "Document: {docGroup.Key}")
For Each barcode In docGroup
Console.WriteLine($" - {barcode.BarcodeType}: {barcode.Text}")
Next barcode
Next docGroup
此並行處理方式能同時處理文件,在多核心系統上可將總掃描時間縮短多達 75%。 若需處理Enterprise級BarCode處理,請參閱我們的效能優化指南。
摘要
IronBarcode 將複雜的 BarCode 掃描轉化為簡潔的 C# 程式碼。 無論您正在開發庫存系統、文件處理程式或行動應用程式,此函式庫皆能處理從完美的數位BARCODE到具挑戰性的實境擷取等各種情境。
涵蓋的主要功能:
- 從圖片中讀取單行BarCode
- 針對損壞或旋轉BarCode的高階選項
- 全面的 PDF 和 TIFF 文件掃描功能
- 透過多執行緒實現高效能批次處理
- 支援所有主要BarCode格式
延伸閱讀
透過以下資源擴展您的BarCode處理能力:
- BarCode生成教學 - 建立自訂BarCode
- QR 碼指南](/csharp/barcode/tutorials/csharp-qr-code-generator/) - 專用的 QR 碼功能
BarcodeReader類別參考 - 完整 API 文件- 疑難排解指南 - 常見問題與解決方案
原始碼下載
請親自執行以下範例:
準備好在您的應用程式中實作BarCode掃描功能了嗎? 立即開始免費試用,為您的 .NET 專案增添 Professional 版 BARCODE 讀取功能。
常見問題
如何在 .NET 項目中安裝條碼閱讀程式庫?
您可以使用命令 dotnet add package BarCode 通過 Visual Studio 的 NuGet 界面或 NuGet Package Manager 安裝 IronBarcode 程式庫。另外,也可下載 DLL 進行手動安裝。
使用 C# 從圖像讀取條碼的方法是什麼?
使用 IronBarcode 的 BarcodeReader.Read 方法,只需一行程式碼:var results = BarcodeReader.Read('image.png'); 此方法會偵測並讀取圖像中所有的條碼格式。
能否在單個圖像或文件中檢測多個條碼?
是的,IronBarcode 可以自動檢測並讀取圖像、PDF 或多重幀 TIFF 中的多個條碼,返回每個條碼的值、類型和位置於 BarcodeResults 集合中。
如何使用 C# 從 PDF 讀取條碼?
使用 IronBarcode 的 BarcodeReader.ReadPdf 方法掃描 PDF 文件的所有頁面:var results = BarcodeReader.ReadPdf('document.pdf'); 每個結果都包含找到條碼的頁碼。
如果條碼圖像模糊或旋轉該怎麼辦?
通過設定 BarcodeReaderOptions 來處理挑戰性圖像,設置 AutoRotate = true 並應用圖像過濾器如 SharpenFilter 或 AdaptiveThresholdFilter。使用 Speed = ExtremeDetail 提升準確度。
在 .NET 應用程序中支持哪些條碼格式?
IronBarcode 支持所有主要條碼格式,如 QR 碼、Code 128、Code 39、EAN-13、UPC-A、Data Matrix、PDF417 等。使用 BarcodeEncoding.All 掃描任何支持的格式。
如何在 C# 應用程序中提升條碼掃描性能?
通過指定期望的條碼類型 ExpectBarcodeTypes、啟用多執行緒處理並選擇合適的 Speed 設定提高性能。批處理任務中使用帶路徑的 BarcodeReader.Read。
處理條碼讀取錯誤的建議方法是什麼?
將條碼讀取包裝在 try-catch 塊中,並驗證結果是否為空或空白。IronBarcode 提供詳細的錯誤信息和一個 Confidence 屬性以指示檢測的可靠性。
掃描後能夠提取條碼圖像嗎?
是的,IronBarcode 的 BarcodeResult 包含一個 BarcodeImage 屬性,包含偵測到的條碼位圖,可以單獨保存或處理。
如何從 PDF 文檔中指定頁面讀取條碼?
在 BarcodeReaderOptions 中設置 PageNumbers 屬性指定頁面:options.PageNumbers = new[] {1, 2, 3};,通過僅掃描指定頁面來優化性能。
哪些圖像格式與 .NET 中的條碼掃描兼容?
IronBarcode 支持掃描 PNG、JPEG、BMP、GIF、TIFF(包括多幀)和 PDF 格式。您可以從文件路徑、流或位元組數組中加載圖像。
如何在 C# 中訪問掃描條碼的二進位數據?
利用 BarcodeResult 的 BinaryValue 屬性獲取原始二進位數據,特別適用於包含壓縮資訊或二進位協議的條碼。

