C# 條碼掃描器:在 .NET 應用程式中讀取條碼與 QR Code
需要在.NET應用程式中快速掃描條碼或二維碼嗎? 無論您是處理完美的數位影像還是具有挑戰性的真實世界照片, IronBarcode能讓條碼讀取變得簡單可靠。 本指南將透過您可以立即使用的實際範例,向您展示如何在 C# 中實現條碼掃描。
快速入門:立即從檔案讀取條碼
這個簡單的範例向您展示了使用IronBarcode入門是多麼容易。 只需一行程式碼,即可從圖像檔案中讀取條碼——無需複雜的設定。
最簡工作流程(5個步驟)
- 從NuGet或透過 DLL 下載安裝IronBarcode
- 使用`BarcodeReader.Read`方法掃描任何條碼或二維碼
- 在單一掃描件、PDF 或多幀 TIFF 檔案中讀取多個條碼或二維碼
- 啟用IronBarcode ,利用進階濾鏡解碼不完美的掃描和照片。
- 下載教學項目並立即開始掃描
如何在我的.NET專案中安裝IronBarcode ?
IronBarcode可以透過NuGet套件管理器輕鬆安裝,也可以直接下載 DLL 檔案進行安裝。 建議使用NuGet安裝,因為它能夠自動管理依賴項和更新。
Install-Package BarCode
安裝完成後,在 C# 檔案中新增 using IronBarCode; 以存取條碼掃描功能。 有關不同開發環境下的詳細安裝說明,請查看我們的安裝指南。
如何使用 C# 讀取我的第一個條碼?
使用IronBarcode讀取條碼只需要一行程式碼。 此庫可自動偵測條碼格式並擷取所有編碼資料。
*IronBarcode可以立即讀取的標準 Code128 條碼*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.Count > 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.Confidence - 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.Count > 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.Confidence - 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 集合,其中包含所有偵測到的條碼。 每個 BarcodeResult 提供對條碼的文字值、格式類型、位置座標和二進位資料的存取。 這種方法可以與常見的條碼格式無縫配合,包括 Code128、Code39、QR 碼和 Data Matrix 碼。
哪些方法可以幫助讀取難以辨識或損壞的條碼?
現實世界中的條碼掃描經常會遇到影像不完美的情況——角度傾斜、光線不足或部分損壞。 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.Code128,
// 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.Code128,
// 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
Private options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.ExtremeDetail,
.ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
.MaxParallelThreads = 4,
.CropArea = Nothing
}
' Apply options when reading
Private 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使用進階選項成功讀取了旋轉後的二維碼*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.Confidence}%");
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.Confidence}%");
Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
Imports IronBarCode
Private options As New BarcodeReaderOptions With {
.ImageFilters = New ImageFilterCollection From {
New AdaptiveThresholdFilter(9, 0.01F),
New ContrastFilter(2.0F),
New SharpenFilter()
},
.AutoRotate = True,
.Multithreaded = True
}
Private 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 result
IronBarcode 的這些進階功能使其成為掃描照片、監視器或行動裝置拍攝的影像中條碼的理想選擇,尤其適用於影像品質差異很大的情況。
如何掃描PDF文件中的多個條碼?
PDF條碼掃描對於處理發票、出貨標籤和庫存文件至關重要。 IronBarcode可以有效率地讀取每一頁上的所有條碼。
從PDF檔中讀取條碼
using System;
using IronBarCode;
try
{
// Scan all pages of a PDF for barcodes
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
if (results != null && results.Count > 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.Count > 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 barcode
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 頁面中發現了多個條碼
對於特定頁面範圍或進階 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 文件,不同幀上帶有條碼。
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 處理,包括影像濾鏡和旋轉設定。 有關 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%。 對於企業級條碼處理,請查閱我們的效能最佳化指南。
概括
IronBarcode將複雜的條碼掃描轉換為簡單的 C# 程式碼。 無論您是建立庫存系統、文件處理器還是行動應用程式,該庫都能處理從完美的數位條碼到具有挑戰性的現實世界採集的一切。
主要功能涵蓋:
- 從影像中讀取單行條碼
- 針對損壞或旋轉條碼的進階選項
- 全面掃描 PDF 和 TIFF 文檔
- 高效能多執行緒批次處理
支援所有主流條碼格式
延伸閱讀
利用以下資源擴展您的條碼處理能力:
條碼產生教學課程- 建立自訂條碼
- 二維碼指南](/csharp/barcode/tutorials/csharp-qr-code-generator/) - 二維碼的專用功能
BarcodeReader類別參考- 完整的 API 文檔
故障排除指南- 常見問題及解決方案
原始碼下載
請自行執行以下範例:
準備好在您的應用程式中實現條碼掃描了嗎? 立即開始免費試用,並將專業的條碼讀取功能加入您的.NET專案。
立即開始在您的項目中使用 IronBarcode 並免費試用。
常見問題解答
如何在 .NET 項目中安裝條碼讀取庫?
你可以使用命令 dotnet add package BarCode 或通過 Visual Studio 的 NuGet 介面安裝 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 屬性獲取原始二進制數據,對於包含非文本數據(如壓縮信息或二進制協議)的條碼特別有用。

