如何在C#中一次讀取多個條碼

如何在 C# 中一次讀取多個 BarCode;

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronBarcode 可透過設定 ExpectMultipleBarcodes = true 從影像和 PDF 中同時讀取多個條碼,簡化物流、零售和庫存管理應用程式的資料處理。 無論是建立倉儲系統、零售點銷售應用程式或文件處理解決方案,IronBarcode先進的讀取功能都能提供您所需的可靠性和效能。

快速入門:輕鬆讀取影像中的所有條碼

本範例展示如何快速使用 IronBarcode 掃描影像,以獲得其中包含的每個條碼。 只需在您想要的 BarCode 類型旁邊設定 ExpectMultipleBarcodes = true--沒有模板,沒有麻煩。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronBarcode

    PM > Install-Package BarCode

  2. 複製並運行這段程式碼。

    var results = IronBarCode.BarcodeReader.Read("image.png", new IronBarCode.BarcodeReaderOptions { ExpectMultipleBarcodes = true, ExpectBarcodeTypes = IronBarCode.BarcodeEncoding.AllOneDimensional });
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronBarcode,免費試用!
    arrow pointer


如何從影像讀取多個 BarCode?

預設情況下,IronBarcode 會持續掃描文件以讀取多個條碼。 然而,曾有即使存在多個 BarCode,也只傳回一個條碼值的情況。 為解決這個問題,請自訂設定以啟用讀取多個 BarCode,如下所示。 ExpectMultipleBarcodes 屬性同時存在於 BarcodeReaderOptionsPdfBarcodeReaderOptions 類別中,讓您可以使用它來 讀取影像和 PDF 文件中的條碼

標示為 A、B 和 C 的三個條碼樣本,顯示多條碼讀取示範的不同條碼模式
:path=/static-assets/barcode/content-code-examples/how-to/read-multiple-barcodes-read-multiple-barcodes.cs
using IronBarCode;
using System;

// Set the option to read multiple barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = true,
    ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional,
};

// Read barcode
var results = BarcodeReader.Read("testbc1.png", options);

foreach (var result in results)
{
    Console.WriteLine(result.ToString());
}
Imports IronBarCode
Imports System

' Set the option to read multiple barcodes
Private options As New BarcodeReaderOptions() With {
	.ExpectMultipleBarcodes = True,
	.ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional
}

' Read barcode
Private results = BarcodeReader.Read("testbc1.png", options)

For Each result In results
	Console.WriteLine(result.ToString())
Next result
$vbLabelText   $csharpLabel

ExpectMultipleBarcodes 設定為 true 可使 IronBarcode 掃描整個文件以獲得多個條碼,並將其儲存於 BarcodeResults 變數中。 使用 foreach 環路,您可以輕鬆存取並列印所有 BarCode 值到控制台。

進階多重條碼讀取情境

在處理多個 BarCode 時,您可能會遇到需要額外設定的情況。 以下是一個綜合範例,示範如何從複雜的文件中讀取不同格式的多個 BarCode:

using IronBarCode;
using System;
using System.Linq;

// Configure advanced options for mixed barcode types
BarcodeReaderOptions advancedOptions = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = true,
    // Read both 1D and 2D barcodes
    ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional | BarcodeEncoding.QRCode | BarcodeEncoding.DataMatrix,
    // Apply image correction filters for better accuracy
    ImageFilters = new ImageFilterCollection() {
        new SharpenFilter(),
        new ContrastFilter()
    },
    // Set speed vs accuracy balance
    Speed = ReadingSpeed.Balanced
};

// Read from various sources
var imageResults = BarcodeReader.Read("mixed-barcodes.jpg", advancedOptions);
var pdfResults = BarcodeReader.ReadPdf("document-with-barcodes.pdf", advancedOptions);

// Process results with error handling
foreach (var result in imageResults)
{
    Console.WriteLine($"Barcode Type: {result.BarcodeType}");
    Console.WriteLine($"Value: {result.Value}");
    Console.WriteLine($"Confidence: {result.Confidence}%");
    Console.WriteLine($"Page: {result.PageNumber}");
    Console.WriteLine("---");
}
using IronBarCode;
using System;
using System.Linq;

// Configure advanced options for mixed barcode types
BarcodeReaderOptions advancedOptions = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = true,
    // Read both 1D and 2D barcodes
    ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional | BarcodeEncoding.QRCode | BarcodeEncoding.DataMatrix,
    // Apply image correction filters for better accuracy
    ImageFilters = new ImageFilterCollection() {
        new SharpenFilter(),
        new ContrastFilter()
    },
    // Set speed vs accuracy balance
    Speed = ReadingSpeed.Balanced
};

// Read from various sources
var imageResults = BarcodeReader.Read("mixed-barcodes.jpg", advancedOptions);
var pdfResults = BarcodeReader.ReadPdf("document-with-barcodes.pdf", advancedOptions);

// Process results with error handling
foreach (var result in imageResults)
{
    Console.WriteLine($"Barcode Type: {result.BarcodeType}");
    Console.WriteLine($"Value: {result.Value}");
    Console.WriteLine($"Confidence: {result.Confidence}%");
    Console.WriteLine($"Page: {result.PageNumber}");
    Console.WriteLine("---");
}
Imports IronBarCode
Imports System
Imports System.Linq

' Configure advanced options for mixed barcode types
Dim advancedOptions As New BarcodeReaderOptions() With {
    .ExpectMultipleBarcodes = True,
    ' Read both 1D and 2D barcodes
    .ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional Or BarcodeEncoding.QRCode Or BarcodeEncoding.DataMatrix,
    ' Apply image correction filters for better accuracy
    .ImageFilters = New ImageFilterCollection() From {
        New SharpenFilter(),
        New ContrastFilter()
    },
    ' Set speed vs accuracy balance
    .Speed = ReadingSpeed.Balanced
}

' Read from various sources
Dim imageResults = BarcodeReader.Read("mixed-barcodes.jpg", advancedOptions)
Dim pdfResults = BarcodeReader.ReadPdf("document-with-barcodes.pdf", advancedOptions)

' Process results with error handling
For Each result In imageResults
    Console.WriteLine($"Barcode Type: {result.BarcodeType}")
    Console.WriteLine($"Value: {result.Value}")
    Console.WriteLine($"Confidence: {result.Confidence}%")
    Console.WriteLine($"Page: {result.PageNumber}")
    Console.WriteLine("---")
Next
$vbLabelText   $csharpLabel

這個進階範例展示了幾個重要的功能:

如何讀取單一 BarCode 以獲得更好的效能?

IronBarcode 可讀取影像或 PDF 中的單一或多重條碼。 預設情況下,即使只有一個 BarCode,引擎也會掃描整個文件。 為了提高讀取單一 BarCode 時的效能,請將 ExpectMultipleBarcodes 設為 false。 這可以讓引擎在偵測到第一個 BarCode 之後不再掃描整個文件,進而加快條碼擷取的速度。 下面的程式碼展示了這種方法。

<! -- 顯示單一與多重 BarCode 讀取速度的效能比較圖 --> <!--說明:比較單一與多重 BarCode 讀取模式處理時間的圖表 -->

三個完全相同的條碼樣本,分別標示為 A、B 和 C,用於條碼讀取示範
:path=/static-assets/barcode/content-code-examples/how-to/read-multiple-barcodes-read-single-barcode.cs
using IronBarCode;
using System;

// Set the option to read single barcode
BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = false,
    ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional,
};

// Read barcode
var results = BarcodeReader.Read("testbc1.png", options);

foreach (var result in results)
{
    Console.WriteLine(result.ToString());
}
Imports IronBarCode
Imports System

' Set the option to read single barcode
Private options As New BarcodeReaderOptions() With {
	.ExpectMultipleBarcodes = False,
	.ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional
}

' Read barcode
Private results = BarcodeReader.Read("testbc1.png", options)

For Each result In results
	Console.WriteLine(result.ToString())
Next result
$vbLabelText   $csharpLabel

在這個範例中,我們使用與之前相同的具有多個 BarCode 的圖片,但將 ExpectMultipleBarcodes 設為 false。 因此,只會傳回第一個條碼值,掃描過程在檢索到第一個條碼後停止。

使用裁剪區域優化單一條碼讀取

為了在讀取單一 BarCode 時獲得更好的效能,請結合 ExpectMultipleBarcodes = false 設定與 裁剪區域規格。 當您知道 BarCode 的大概位置時,此技術尤其有用:

using IronBarCode;
using IronSoftware.Drawing;

// Define a crop region where the barcode is likely located
var cropRegion = new Rectangle(100, 100, 300, 200);

// Configure options for optimal single barcode reading
BarcodeReaderOptions optimizedOptions = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = false,
    ExpectBarcodeTypes = BarcodeEncoding.Code128,
    CropArea = cropRegion,
    Speed = ReadingSpeed.Faster
};

// Read with optimized settings
var result = BarcodeReader.Read("product-label.png", optimizedOptions).FirstOrDefault();

if (result != null)
{
    Console.WriteLine($"Barcode found: {result.Value}");
    Console.WriteLine($"Read time: {result.ReadTime}ms");
}
using IronBarCode;
using IronSoftware.Drawing;

// Define a crop region where the barcode is likely located
var cropRegion = new Rectangle(100, 100, 300, 200);

// Configure options for optimal single barcode reading
BarcodeReaderOptions optimizedOptions = new BarcodeReaderOptions()
{
    ExpectMultipleBarcodes = false,
    ExpectBarcodeTypes = BarcodeEncoding.Code128,
    CropArea = cropRegion,
    Speed = ReadingSpeed.Faster
};

// Read with optimized settings
var result = BarcodeReader.Read("product-label.png", optimizedOptions).FirstOrDefault();

if (result != null)
{
    Console.WriteLine($"Barcode found: {result.Value}");
    Console.WriteLine($"Read time: {result.ReadTime}ms");
}
Imports IronBarCode
Imports IronSoftware.Drawing

' Define a crop region where the barcode is likely located
Dim cropRegion As New Rectangle(100, 100, 300, 200)

' Configure options for optimal single barcode reading
Dim optimizedOptions As New BarcodeReaderOptions() With {
    .ExpectMultipleBarcodes = False,
    .ExpectBarcodeTypes = BarcodeEncoding.Code128,
    .CropArea = cropRegion,
    .Speed = ReadingSpeed.Faster
}

' Read with optimized settings
Dim result = BarcodeReader.Read("product-label.png", optimizedOptions).FirstOrDefault()

If result IsNot Nothing Then
    Console.WriteLine($"Barcode found: {result.Value}")
    Console.WriteLine($"Read time: {result.ReadTime}ms")
End If
$vbLabelText   $csharpLabel

單一條碼讀取速度有多快?

ExpectMultipleBarcodes 設為 false 可大幅提升讀取單一 BarCode 的效率。 在處理高解析度影像或在高吞吐量應用程式中實作 異步條碼讀取時,效能提升尤其顯著。

使用提供的程式碼片段,以下是同一台機器上將ExpectMultipleBarcodes設為 true 和 false 時效能差異的粗略估計:

ExpectMultipleBarcodes = true ExpectMultipleBarcodes = false
0.91秒 0.10 秒

在讀取單一 BarCode 時,這代表大約 9 倍的效能提升。 實際的效能增益依下列因素而有所不同:

  • 影像解析度與複雜度
  • 圖片中出現的 BarCode 數量
  • 選取的 BarCode 格式
  • 應用影像濾鏡
  • 硬體規格

多重條碼讀取的最佳實務

在生產應用程式中實作多重 BarCode 讀取時,請考慮這些最佳實務:

1.指定期望的條碼類型:不要使用 BarcodeEncoding.All 而只指定您期望的格式。 這可大幅提升效能。

2.使用適當的圖像格式:為達到最佳效果,請使用高對比度的圖片。 進一步了解 建立最佳條碼影像

3.處理不完美的 BarCode:現實世界中的 BarCode 可能會損壞或印刷不良。 使用影像修正技術來提高閱讀成功率。

4.串流處理:對於大量批次,請考慮 從串流讀取,以最佳化記憶體使用。

5.錯誤處理:對於無法讀取 BarCode 的情況,請務必執行適當的錯誤處理:

try
{
    var results = BarcodeReader.Read("barcodes.png", new BarcodeReaderOptions 
    { 
        ExpectMultipleBarcodes = true 
    });

    if (!results.Any())
    {
        Console.WriteLine("No barcodes found in the image");
    }
    else
    {
        Console.WriteLine($"Found {results.Count()} barcodes");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading barcodes: {ex.Message}");
    // Log error for debugging
}
try
{
    var results = BarcodeReader.Read("barcodes.png", new BarcodeReaderOptions 
    { 
        ExpectMultipleBarcodes = true 
    });

    if (!results.Any())
    {
        Console.WriteLine("No barcodes found in the image");
    }
    else
    {
        Console.WriteLine($"Found {results.Count()} barcodes");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading barcodes: {ex.Message}");
    // Log error for debugging
}
Imports System

Try
    Dim results = BarcodeReader.Read("barcodes.png", New BarcodeReaderOptions With {
        .ExpectMultipleBarcodes = True
    })

    If Not results.Any() Then
        Console.WriteLine("No barcodes found in the image")
    Else
        Console.WriteLine($"Found {results.Count()} barcodes")
    End If
Catch ex As Exception
    Console.WriteLine($"Error reading barcodes: {ex.Message}")
    ' Log error for debugging
End Try
$vbLabelText   $csharpLabel

遵循這些實踐並運用 IronBarcode 的全面功能,您可以建立強大的應用程式,有效地處理各行各業和使用個案中的多種條碼讀取情境。

常見問題解答

如何在 C# 中從單一影像讀取多個 BarCode?

使用 IronBarcode,您可以在 BarcodeReaderOptions 中設定 ExpectMultipleBarcodes = true,從單一影像讀取多個條碼。這使得 IronBarcode 可以掃描整個文件,並在一個 BarcodeResults 集合中返回所有找到的條碼,您可以遍歷該集合。

掃描影像中所有 BarCode 的最快方法是什麼?

最快的方法是使用 IronBarcode 的讀取方法,且 ExpectMultipleBarcodes = true: var results = IronBarCode.BarcodeReader.Read("image.png", new IronBarCode.BarcodeReaderOptions { ExpectMultipleBarcodes = true })。這個最小的程式碼不需要複雜的設定就能擷取所有的 BarCode 值。

我可以從 PDF 文件以及影像讀取多個 BarCode 嗎?

是的,IronBarcode 支持从图像和 PDF 文档中读取多个条码。ExpectMultipleBarcodes 属性在 BarcodeReaderOptions 和 PdfBarcodeReaderOptions 类中都可用,允许您为任何文档类型配置多条码读取。

如果不將 ExpectMultipleBarcodes 設為 true 會發生什麼情況?

預設情況下,IronBarcode 會持續掃描文件中的多個條碼。然而,在某些情況下,即使存在多個條碼,也可能只返回一個條碼值。顯式地設定 ExpectMultipleBarcodes = true 可確保 IronBarcode 掃描並回傳文件中的所有條碼。

讀取多個 BarCode 後,如何存取個別的條碼值?

使用 IronBarcode 讀取多個條碼後,結果會儲存在 BarcodeResults 變數中。您可以使用 foreach 環路輕鬆存取個別條碼的值,以遍歷集合並處理每個條碼的值、文字和格式屬性。

讀取多個 BarCode 是否適合零售和物流應用?

是的,IronBarcode 的多重條碼讀取能力是零售點銷售系統、倉儲管理、物流追蹤和庫存管理應用程式的理想選擇。它能同時有效地掃描出貨標籤、產品目錄或庫存單中的所有 BarCode,從而簡化資料處理流程。

當讀取多個 BarCode 時,我可以指定要尋找哪些條碼類型嗎?

是的,IronBarcode 允許您使用 ExpectBarcodeTypes 屬性指定預期的條碼類型。您可以將其設置為掃描特定格式,如 AllOneDimensional、QRCode 或任何支援條碼類型的組合,以優化掃描性能。

設定 ExpectMultipleBarcodes 會影響掃描效能嗎?

當您知道文件中只存在一個條碼時,設定 ExpectMultipleBarcodes = false 可以提高性能。IronBarcode 會在找到第一個條碼後停止掃描,使其在單一條碼的情況下速度更快,同時在需要時仍提供多條碼讀取的彈性。

Hairil Hasyimi Bin Omar
軟體工程師
就像所有優秀的工程師一樣,Hairil 也是一位狂熱的學習者。他不斷精進 C#、Python 和 Java 的知識,利用這些知識為整個 Iron Software 的團隊成員增加價值。Hairil 從馬來西亞的 Universiti Teknologi MARA 大學加入 Iron Software 團隊,畢業於該校的化學與流程工程學系,並取得學士學位。
準備好開始了嗎?
Nuget 下載 2,070,733 | 版本: 2026.2 剛剛發布