如何在 C# 中驗證 BarCode 校驗和並使用格式感知讀取功能

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

條碼校驗和有助於偵測替換錯誤。 例如,EAN-13 標籤中一個數字顛倒就可能導致包裹被送到錯誤的倉庫。 格式感知讀取透過將解碼器限制為預期的符號體系,提供了額外的驗證層。 這種方法透過跳過不必要的格式偵測器來減少背景雜訊造成的誤報並縮短掃描時間。

IronBarcode在解碼過程中會自動執行校驗和驗證。 每種條碼編碼的校驗位演算法預設運行,失敗的條碼會在傳回結果之前被丟棄。 BarcodeReaderOptions.ExpectBarcodeTypes 屬性將讀取限制為特定格式,而 RemoveFalsePositive 則增加了模糊讀取的二次掃描。

本指南說明如何驗證條碼校驗和,將讀取限制為預期格式,並將這兩種技術結合到使用 BarcodeReaderOptions 的分層品質閘中。

快速入門:透過校驗碼與格式限制驗證BarCode

配置 BarcodeReaderOptionsExpectBarcodeTypesRemoveFalsePositive,以將讀取限制為預期符號體系,並自動進行校驗和驗證。

:path=/static-assets/barcode/content-code-examples/how-to/checksum-and-format-validation/quickstart.cs
using IronBarCode;

// Format-constrained read with false-positive removal.
// Limit the decoder to EAN-13 and Code128; checksums are
// validated automatically and failures are silently discarded.
var options = new BarcodeReaderOptions
{
    ExpectBarcodeTypes  = BarcodeEncoding.EAN13 | BarcodeEncoding.Code128,
    RemoveFalsePositive = true,
    Speed               = ReadingSpeed.Balanced
};

BarcodeResults results = BarcodeReader.Read("label.png", options);
Imports IronBarCode

' Format-constrained read with false-positive removal.
' Limit the decoder to EAN-13 and Code128; checksums are
' validated automatically and failures are silently discarded.
Dim options As New BarcodeReaderOptions With {
    .ExpectBarcodeTypes = BarcodeEncoding.EAN13 Or BarcodeEncoding.Code128,
    .RemoveFalsePositive = True,
    .Speed = ReadingSpeed.Balanced
}

Dim results As BarcodeResults = BarcodeReader.Read("label.png", options)
$vbLabelText   $csharpLabel

如何驗證BarCode校驗碼?

IronBarcode在解碼過程中會根據每種符號系統的規範驗證校驗和。 例如,讀取 EAN-13 條碼時,模組10 校驗位元由前 12 位數字計算得出,並與第 13 位進行比較。 如果數字不匹配,則條碼將被默默拒絕,並且不會出現在 BarcodeResults 集合中。 這種方法適用於所有具有強制校驗位的格式,包括 UPC-A、UPC-E、EAN-8、Code128、ITF 等。

此隱式模型有別於提供明確切換開關的函式庫。 下表比較了這兩種方法:

校驗與驗證模型比較: IronBarcode與 Aspose.Barcode
範疇IronBarcodeAspose.BarCode
驗證觸發條件自動運行;每次解碼期間運行顯式: 校驗碼Validation.On / Off / Default
開發者需採取的行動無;無效條碼已從結果中排除。讀取條碼前,請設定BarcodeSettings.校驗碼Validation
校驗和停用未公開;強制格式始終強制執行校驗和。是的; 校驗碼Validation.Off會跳過驗證
可選校驗碼格式 (Code39)使用Confidence + RemoveFalsePositive過濾低品質讀取數據明確啟用Enable校驗碼.是
失敗行為BarCode已從結果中隱去條碼可能帶有單獨的校驗和值,以便人工檢查。

對於具有可選校驗和的符號系統(例如 Code39),該庫使用置信度評分和 RemoveFalsePositive 而不是校驗和切換。

輸入

Code128 倉庫貨架標籤(成功路徑)和沒有條碼的空白影像(失敗路徑)。

Code128 barcode encoding RACK-A1-LOT-7382 used as the warehouse rack scan input

warehouse-rack.png(成功路徑)

Blank white image with no barcode to trigger the empty result path

blank-no-barcode.png(失敗路徑-無條碼)

:path=/static-assets/barcode/content-code-examples/how-to/checksum-and-format-validation/checksum-confidence.cs
using IronBarCode;

// Constrain reads to 1D formats and enable secondary verification.
// ConfidenceThreshold rejects decodes where the ML detector falls below 85%,
// acting as a quality gate for optional-checksum symbologies like Code39.
var options = new BarcodeReaderOptions
{
    ExpectBarcodeTypes  = BarcodeEncoding.AllOneDimensional,
    RemoveFalsePositive = true,
    ConfidenceThreshold = 0.85,
    Speed               = ReadingSpeed.Detailed
};

BarcodeResults results = BarcodeReader.Read("warehouse-rack.png", options);

foreach (BarcodeResult result in results)
{
    // Each result has passed checksum validation (mandatory formats)
    // and the 85% confidence threshold, so no additional filtering is needed.
    Console.WriteLine($"[{result.BarcodeType}] {result.Value}  page={result.PageNumber}");
}

if (results.Count == 0)
{
    Console.Error.WriteLine("No valid barcodes found. Possible causes:");
    Console.Error.WriteLine("  - Check digit mismatch (barcode silently rejected)");
    Console.Error.WriteLine("  - Confidence below 85% threshold");
    Console.Error.WriteLine("  - Format not in ExpectBarcodeTypes");
}
Imports IronBarCode

' Constrain reads to 1D formats and enable secondary verification.
' ConfidenceThreshold rejects decodes where the ML detector falls below 85%,
' acting as a quality gate for optional-checksum symbologies like Code39.
Dim options As New BarcodeReaderOptions With {
    .ExpectBarcodeTypes = BarcodeEncoding.AllOneDimensional,
    .RemoveFalsePositive = True,
    .ConfidenceThreshold = 0.85,
    .Speed = ReadingSpeed.Detailed
}

Dim results As BarcodeResults = BarcodeReader.Read("warehouse-rack.png", options)

For Each result As BarcodeResult In results
    ' Each result has passed checksum validation (mandatory formats)
    ' and the 85% confidence threshold, so no additional filtering is needed.
    Console.WriteLine($"[{result.BarcodeType}] {result.Value}  page={result.PageNumber}")
Next

If results.Count = 0 Then
    Console.Error.WriteLine("No valid barcodes found. Possible causes:")
    Console.Error.WriteLine("  - Check digit mismatch (barcode silently rejected)")
    Console.Error.WriteLine("  - Confidence below 85% threshold")
    Console.Error.WriteLine("  - Format not in ExpectBarcodeTypes")
End If
$vbLabelText   $csharpLabel

輸出

成功之路

控制台輸出顯示 Code128 RACK-A1-LOT-7382 的解碼置信度高於閾值。

倉庫貨架條碼在第 0 頁上顯示為 RACK-A1-LOT-7382。它超過了 85% 的置信度閾值並通過了校驗和驗證,因此顯示在 BarcodeResults 中。

故障路徑

控制台輸出顯示警告:未找到空白影像輸入的有效條碼

ConfidenceThreshold 的值提高到其預設值 0.7 以上,可以進一步收緊 Code39 等可選校驗和符號體系的此限制。

校驗和驗證完成後,下一步是將讀取器限制為管道所需的條碼格式。


如何使用格式感知型BarCode讀取功能?

BarcodeEncoding 枚舉類型為標誌類型,允許使用位元或運算子組合多種格式。 設定 ExpectBarcodeTypes 會將讀取器限制為這些格式,並跳過其他格式的偵測。

常見的條碼編碼值
Value類別描述校驗碼
BarcodeEncoding.All元資料所有支援的格式(預設行為)按格式
BarcodeEncoding.AllOneDimensional元資料所有線性(1D)格式,包括堆疊式按格式
BarcodeEncoding.AllTwoDimensional元資料所有矩陣/網格(QR 圖)格式按格式
BarcodeEncoding.Code1281D高密度字母數字字元集(物流、運輸)必選(權重 模組103)
BarcodeEncoding.EAN131D零售產品識別碼,13 位數字必選 (模組10)
BarcodeEncoding.QRCodeQR 圖高容量矩陣(URL、結構化資料)里德-所羅門 ECC
BarcodeEncoding.Code391D字母數字(國防、汽車)可選 (Mod43)
BarcodeEncoding.UPCA1D北美零售,12位數必選 (模組10)
BarcodeEncoding.DataMatrixQR 圖緊湊型矩陣(電子、製藥)里德-所羅門 ECC
BarcodeEncoding.PDF417QR 圖堆疊(身分證、交通卡)里德-所羅門 ECC

除了速度之外,限制格式集還起到驗證門的作用:即使條碼實際存在於圖像中,任何未列出的符號系統的條碼也會被排除在結果之外。

輸入

Code128 運輸標籤(成功路徑)和不符合 Code128 限制的二維碼(失敗路徑)。

Code128 barcode encoding SHIP-2024-00438 used as the shipping label input

shipping-label.png(成功路徑 — Code128 符合約束)

QR code used as the format-mismatch failure path for the Code128-only constrained read

qr-format-mismatch.png(失敗路徑-二維碼被僅支援 Code128 的過濾器拒絕)

:path=/static-assets/barcode/content-code-examples/how-to/checksum-and-format-validation/format-constrained.cs
using IronBarCode;

// Constrained read: only Code128 barcodes are returned.
// Faster because the reader skips all other format detectors.
var constrainedOptions = new BarcodeReaderOptions
{
    ExpectBarcodeTypes     = BarcodeEncoding.Code128,
    Speed                  = ReadingSpeed.Faster,
    ExpectMultipleBarcodes = false
};

// Broad read: all supported formats are scanned.
// Useful for verification or when the image format is unknown.
var broadOptions = new BarcodeReaderOptions
{
    ExpectBarcodeTypes     = BarcodeEncoding.All,
    Speed                  = ReadingSpeed.Detailed,
    ExpectMultipleBarcodes = true
};

string imagePath = "shipping-label.png";

BarcodeResults constrained = BarcodeReader.Read(imagePath, constrainedOptions);
Console.WriteLine($"Constrained: {constrained.Count} Code128 barcode(s) found");

BarcodeResults broad = BarcodeReader.Read(imagePath, broadOptions);
Console.WriteLine($"Broad: {broad.Count} barcode(s) found across all formats");

foreach (BarcodeResult result in broad)
{
    Console.WriteLine($"  [{result.BarcodeType}] {result.Value}");
}
Imports IronBarCode

' Constrained read: only Code128 barcodes are returned.
' Faster because the reader skips all other format detectors.
Dim constrainedOptions As New BarcodeReaderOptions With {
    .ExpectBarcodeTypes = BarcodeEncoding.Code128,
    .Speed = ReadingSpeed.Faster,
    .ExpectMultipleBarcodes = False
}

' Broad read: all supported formats are scanned.
' Useful for verification or when the image format is unknown.
Dim broadOptions As New BarcodeReaderOptions With {
    .ExpectBarcodeTypes = BarcodeEncoding.All,
    .Speed = ReadingSpeed.Detailed,
    .ExpectMultipleBarcodes = True
}

Dim imagePath As String = "shipping-label.png"

Dim constrained As BarcodeResults = BarcodeReader.Read(imagePath, constrainedOptions)
Console.WriteLine($"Constrained: {constrained.Count} Code128 barcode(s) found")

Dim broad As BarcodeResults = BarcodeReader.Read(imagePath, broadOptions)
Console.WriteLine($"Broad: {broad.Count} barcode(s) found across all formats")

For Each result As BarcodeResult In broad
    Console.WriteLine($"  [{result.BarcodeType}] {result.Value}")
Next
$vbLabelText   $csharpLabel

輸出

成功之路

控制台輸出顯示受限讀取找到 1 個 Code128 條碼,寬讀取結果也證實了這一點。

出貨標籤的值為 SHIP-2024-00438。 受限讀取立即檢測到了它,因為 Code128 是過濾器所期望的,而廣泛讀取在所有格式中都確認了相同的結果。

故障路徑

控制台輸出顯示,對二維碼影像進行受限讀取回傳 0 個結果。

受限讀取結果為空是驗證訊號,而不是錯誤; 記錄差異以供審核。

對於混合使用條碼類型的流程(例如,裝箱單上同時包含 EAN-13 產品代碼和 Code128 追蹤編號),請將預期格式結合起來:

:path=/static-assets/barcode/content-code-examples/how-to/checksum-and-format-validation/multi-format-combine.cs
using IronBarCode;

// Combine multiple format flags with | to scan for more than one symbology
// in a single pass. Each BarcodeResult.BarcodeType identifies which format
// was decoded, enabling downstream routing logic per symbology.
var options = new BarcodeReaderOptions
{
    ExpectBarcodeTypes     = BarcodeEncoding.EAN13 | BarcodeEncoding.Code128,
    ExpectMultipleBarcodes = true
};
Imports IronBarCode

' Combine multiple format flags with Or to scan for more than one symbology
' in a single pass. Each BarcodeResult.BarcodeType identifies which format
' was decoded, enabling downstream routing logic per symbology.
Dim options As New BarcodeReaderOptions With {
    .ExpectBarcodeTypes = BarcodeEncoding.EAN13 Or BarcodeEncoding.Code128,
    .ExpectMultipleBarcodes = True
}
$vbLabelText   $csharpLabel

每個傳回的 BarcodeResult.BarcodeType 標識了解碼後的格式,從而實現了下游路由。

哪些條碼符號支援校驗碼驗證?

並非所有BarCode格式都以相同的方式使用校驗和。 下表將常用符號系統與其錯誤偵測特性對應起來,從而說明如何針對每種格式設定 ConfidenceThresholdRemoveFalsePositive

依符碼系統劃分的校驗碼特性
符號系統校驗碼類型是必選的嗎?推薦
EAN-13 / EAN-8模組10預設設定已足夠;始終強制執行校驗和
UPC-A / UPC-E模組10預設設定已足夠;寫入時校驗位自動更正
Code128加權 模組103預設設定已足夠;依規範要求必須使用。
Code39Mod43(可選)ConfidenceThreshold 調高至 0.8+ 並啟用 RemoveFalsePositive
CodabarMod16(可選)與 Code39 相同;使用置信度作為品質門控
ITF模組10(可選)針對交錯格式啟用 RemoveFalsePositive
二維碼/資料矩陣里德-所羅門 ECC總是結構誤差修正;無需額外配置
PDF417里德-所羅門 ECC總是與 QR/DataMatrix 相同;糾錯功能是固有的。

對於 QR、DataMatrix 和 PDF417 等二維符號體系,糾錯功能已整合到編碼結構中。 這些格式無需依賴簡單的校驗位即可從部分損壞中復原。 ConfidenceThreshold 在 ML 檢測階段仍然適用,而解碼步驟則受益於符號系統的內建冗餘。

既然我們已經了解了這兩種技術,讓我們將它們合併成一個可用於生產的單一驗證模式。


如何將校驗和與格式限制結合使用?

生產就緒模式集 ConfidenceThresholdSpeed 位於單一 BarcodeReaderOptions 物件中。 它們共同構成了一個分層閘:格式約束縮小了搜尋空間,校驗和驗證確保了資料完整性,置信度閾值過濾了邊緣解碼,而誤報消除則增加了一次二次驗證。

輸入

成功路徑使用了來自 pos-scans/ 目錄的三個 POS 掃描條碼:兩個 EAN-13 和一個 UPC-A。 Code128 倉庫貨架標籤被用作故障路徑——EAN-13/UPC-A 約束拒絕它,並記錄了 REJECT 行。

EAN-13 barcode encoding 5901234123471 used as POS scan input 1

pos-scan-1.png(成功)

EAN-13 barcode encoding 4006381333931 used as POS scan input 2

pos-scan-2.png(成功)

UPC-A barcode encoding 012345678905 used as POS scan input 3

pos-scan-3.png(成功)

Code128 barcode encoding RACK-A1-LOT-7382 used as the combined-validation failure path input

warehouse-rack.png(失敗-代碼128被拒絕)

:path=/static-assets/barcode/content-code-examples/how-to/checksum-and-format-validation/combined-validation.cs
using IronBarCode;

// Layered validation for retail POS: EAN-13, UPC-A, and UPC-E only.
// Each property adds a distinct filter to the read pipeline.
var options = new BarcodeReaderOptions
{
    // Layer 1: format constraint, accept only retail symbologies
    ExpectBarcodeTypes = BarcodeEncoding.EAN13 | BarcodeEncoding.UPCA | BarcodeEncoding.UPCE,

    // Layer 2: confidence threshold, reject decodes below 80%
    ConfidenceThreshold = 0.8,

    // Layer 3: false-positive removal, runs a secondary verification pass
    RemoveFalsePositive = true,

    Speed                  = ReadingSpeed.Balanced,
    ExpectMultipleBarcodes = false,

    // Require 3 agreeing scan lines to reduce phantom reads from noisy images
    MinScanLines = 3
};

string[] scanFiles = Directory.GetFiles("pos-scans/", "*.png");

foreach (string file in scanFiles)
{
    BarcodeResults results = BarcodeReader.Read(file, options);

    if (results.Count == 0)
    {
        // No barcode passed all validation layers
        Console.Error.WriteLine($"REJECT {Path.GetFileName(file)}: "
            + "no valid EAN-13/UPC barcode (checksum, confidence, or format mismatch)");
        continue;
    }

    BarcodeResult primary = results.First();

    // Post-read assertion: verify the decoded format matches expectations.
    // ExpectBarcodeTypes already constrains the reader; this check documents
    // intent and surfaces unexpected results during future changes.
    if (primary.BarcodeType != BarcodeEncoding.EAN13
        && primary.BarcodeType != BarcodeEncoding.UPCA
        && primary.BarcodeType != BarcodeEncoding.UPCE)
    {
        Console.Error.WriteLine($"UNEXPECTED FORMAT {Path.GetFileName(file)}: "
            + $"got {primary.BarcodeType}, expected EAN-13/UPC");
        continue;
    }

    Console.WriteLine($"OK {Path.GetFileName(file)}: [{primary.BarcodeType}] {primary.Value}");
}
Imports IronBarCode
Imports System.IO

' Layered validation for retail POS: EAN-13, UPC-A, and UPC-E only.
' Each property adds a distinct filter to the read pipeline.
Dim options As New BarcodeReaderOptions With {
    ' Layer 1: format constraint, accept only retail symbologies
    .ExpectBarcodeTypes = BarcodeEncoding.EAN13 Or BarcodeEncoding.UPCA Or BarcodeEncoding.UPCE,

    ' Layer 2: confidence threshold, reject decodes below 80%
    .ConfidenceThreshold = 0.8,

    ' Layer 3: false-positive removal, runs a secondary verification pass
    .RemoveFalsePositive = True,

    .Speed = ReadingSpeed.Balanced,
    .ExpectMultipleBarcodes = False,

    ' Require 3 agreeing scan lines to reduce phantom reads from noisy images
    .MinScanLines = 3
}

Dim scanFiles As String() = Directory.GetFiles("pos-scans/", "*.png")

For Each file As String In scanFiles
    Dim results As BarcodeResults = BarcodeReader.Read(file, options)

    If results.Count = 0 Then
        ' No barcode passed all validation layers
        Console.Error.WriteLine($"REJECT {Path.GetFileName(file)}: " &
            "no valid EAN-13/UPC barcode (checksum, confidence, or format mismatch)")
        Continue For
    End If

    Dim primary As BarcodeResult = results.First()

    ' Post-read assertion: verify the decoded format matches expectations.
    ' ExpectBarcodeTypes already constrains the reader; this check documents
    ' intent and surfaces unexpected results during future changes.
    If primary.BarcodeType <> BarcodeEncoding.EAN13 AndAlso
       primary.BarcodeType <> BarcodeEncoding.UPCA AndAlso
       primary.BarcodeType <> BarcodeEncoding.UPCE Then
        Console.Error.WriteLine($"UNEXPECTED FORMAT {Path.GetFileName(file)}: " &
            $"got {primary.BarcodeType}, expected EAN-13/UPC")
        Continue For
    End If

    Console.WriteLine($"OK {Path.GetFileName(file)}: [{primary.BarcodeType}] {primary.Value}")
Next
$vbLabelText   $csharpLabel

輸出

成功之路

控制台輸出顯示所有 3 個 POS 掃描條碼均已接受,狀態為 OK,並已解碼。

三張POS掃描影像全部通過。 讀取器傳回了 4006381333931012345678905 的值。 每個都與"EAN13"匹配 | 上層控制區 | UPCE` 濾波器具有有效的 模組10 校驗和,置信度高於 0.8。

故障路徑

控制台輸出顯示倉庫貨架上的 Code128 條碼被 EAN-13/UPC-A 過濾器拒絕

MinScanLines 設為 3 會增加 1D 條碼有效所需的最小一致掃描線數; 預設值為 2。提高此值可降低雜訊掃描線出現虛假讀取的風險,但可能會導致漏檢細小或部分損壞的條碼。 在零售 POS 環境中,如果標籤列印清晰,則取值為 3 是保守的選擇,可以在不影響吞吐量的情況下加強驗證。

讀取後的 BarcodeType 斷言是一種縱深防禦:ExpectBarcodeTypes 已經進行了過濾,但顯式檢查記錄了意圖,並在不增加運行時成本的情況下捕獲了配置偏差。為了進行速度調優,ReadingSpeed.Faster 適用於乾淨的機器列印標籤; DetailedExtremeDetail 可以恢復損壞或光線不足的條碼,但代價是掃描時間更長。


接下來我該怎麼做?

本文介紹了 IronBarcode 的隱式校驗和驗證模型、格式受限讀取的 BarcodeEncoding 標誌枚舉,以及使用 ExpectBarcodeTypesConfidenceThresholdRemoveFalsePositiveMinScanLines 作為分層品質閘的組合驗證模式。

如需進一步閱讀,請參閱以下資源:

立即申請免費試用授權,在實際環境中測試所有功能;或待開發流程準備就緒投入生產環境時,查看授權選項

常見問題解答

What is barcode checksum validation?

Barcode checksum validation is a process that ensures the accuracy of barcode data by verifying the calculated checksum against the value encoded within the barcode. This helps in detecting errors in the scanning process.

How does IronBarcode handle checksum validation?

IronBarcode implicitly handles checksum validation by calculating the checksum for the barcode data and verifying it against the encoded checksum, ensuring data integrity during the scanning process.

What are BarcodeEncoding filters?

BarcodeEncoding filters in IronBarcode allow you to specify which barcode formats to read or ignore during scanning, enabling more accurate and efficient barcode processing by focusing on specific barcode types.

Can IronBarcode perform combined validation?

Yes, IronBarcode can perform combined validation by checking both the checksum and the format of barcodes during the scanning process, ensuring that only valid and correctly formatted barcodes are processed.

Is it possible to constrain barcode reads by format in C# with IronBarcode?

Yes, IronBarcode allows you to constrain barcode reads by specifying the formats you want to include or exclude, ensuring that your application processes only relevant barcode types.

Why is format-aware reading important in barcode processing?

Format-aware reading is important because it allows your application to process only specific types of barcodes, improving speed and accuracy by ignoring irrelevant or unsupported barcode formats.

How do I implement format-aware reading in IronBarcode?

To implement format-aware reading in IronBarcode, use BarcodeEncoding filters to specify the barcode formats you wish to read. This can be done through the library's API, which allows for precise control over barcode scanning requirements.

What are the benefits of using IronBarcode for barcode validation?

IronBarcode offers several benefits for barcode validation, including robust checksum verification, format-aware reading, and the ability to handle a wide range of barcode standards, ensuring high accuracy and flexibility in barcode processing.

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。

準備好開始了嗎?
Nuget 下載 2,143,620 | 版本: 2026.4 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。