如何在 C# 中驗證 BarCode 校驗和數值並使用格式感知讀取功能
BarCode校驗碼有助於偵測替換錯誤。 舉例來說,EAN-13 條碼標籤中若有一位數字錯位,便可能導致包裹被送往錯誤的倉庫。 格式感知讀取透過將解碼器限制在預期的符碼系統內,提供額外的驗證層。 此方法可減少背景雜訊造成的誤判,並透過跳過不必要的格式偵測器來縮短掃描時間。
IronBarcode 會在解碼過程中自動執行校驗和驗證。 每個符號體系的校驗位演算法預設皆會執行,且在回傳結果前,會先剔除驗證失敗的BarCode。 BarcodeReaderOptions.ExpectBarcodeTypes 屬性將讀取限制在特定格式,而 RemoveFalsePositive 則針對模糊讀取結果增加二次掃描。
本指南說明如何驗證BarCode校驗和、將讀取結果限制在預期格式內,並結合這兩項技術,透過 BarcodeReaderOptions 建立分層品質檢查機制。
快速入門:透過校驗和與格式限制驗證BarCode
將 BarcodeReaderOptions 與 ExpectBarcodeTypes 及 RemoveFalsePositive 搭配使用,可透過自動校驗和驗證機制,將讀取範圍限制在預期的符碼系統內。
: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)
簡化工作流程(5 個步驟)
- 從 NuGet 下載 IronBarcode程式庫
- 建立一個
BarcodeReaderOptions實例 - 將
ExpectBarcodeTypes設定為管線中存在的條碼符號 - 啟用
RemoveFalsePositive進行二次驗證 - 呼叫
BarcodeReader.Read進行解碼,校驗碼會在解碼過程中自動驗證
如何驗證BarCode校驗碼?
IronBarcode 會根據各條碼規格,在解碼過程中驗證校驗和。 例如,在讀取 EAN-13 BARCODE 時,會根據前 12 位數字計算 Mod10 校驗位,並與第 13 位數字進行比對。 若數字不符,BARCODE將被靜默拒絕,且不會出現在 BarcodeResults 集合中。 此方法適用於所有具有強制性校驗位數的格式,包括 UPC-A、UPC-E、EAN-8、Code128、ITF 及其他格式。
此隱式模型有別於提供明確開關選項的函式庫。 下表比較了這兩種方法:
| 要點 | IronBarcode | Aspose.BarCode |
|---|---|---|
| 驗證觸發器 | 自動執行;於每次解碼時運行 | 明確:校驗碼Validation.On / Off / Default |
| 開發者需採取的行動 | 無;無效BarCode將從結果中排除 | 在讀取前請設定 BarcodeSettings.校驗碼Validation |
| 校驗碼停用 | 未公開;強制格式時始終執行校驗和檢查 | 是的;校驗碼Validation.Off 會跳過驗證 |
| 可選校驗碼格式 (Code39) | 使用 Confidence + RemoveFalsePositive 過濾低品質讀取 | 請透過 Enable校驗碼.是的 明確啟用 |
| 錯誤處理行為 | BarCode已從結果中隱去 | BarCode可能會附帶獨立的校驗值,供人工檢查使用 |
對於具有可選校驗碼的條碼符號(例如 Code39),該函式庫採用信心評分機制,並使用 RemoveFalsePositive 取代校驗碼切換功能。
輸入
一張 Code128 倉儲貨架標籤(成功案例)與一張無 BarCode 的空白圖片(失敗案例)。
warehouse-rack.png (成功路徑)
blank-no-BARCODE.png(失敗路徑 — 無BARCODE)
: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
輸出
成功路徑
倉庫貨架的BARCODE在第 0 頁顯示為 RACK-A1-LOT-7382。由於其通過了 85% 的信心閾值並通過校驗和驗證,因此顯示為 BarcodeResults。
失敗路徑
將 ConfidenceThreshold 提升至高於其 0.7 的預設值,將進一步收緊此門檻,適用於 Code39 等可選校驗碼符號體系。
在完成校驗碼驗證後,下一步是將讀取範圍限制在您的處理流程所支援的BARCODE格式內。
如何使用格式感知型BarCode讀取功能?
BarcodeEncoding 枚舉是一種旗標類型,允許透過位元或運算子組合多種格式。 設定 ExpectBarcodeTypes 會將讀取範圍限制於這些格式,並跳過對其他格式的偵測。
| 價值 | 類別 | 描述 | 校驗碼 |
|---|---|---|---|
BarcodeEncoding.All | 元資料 | 所有支援的格式(預設行為) | 按格式 |
BarcodeEncoding.AllOneDimensional | 元資料 | 所有線性(1D)格式,包括堆疊式 | 按格式 |
BarcodeEncoding.AllTwoDimensional | 元資料 | 所有矩陣/網格(2D)格式 | 按格式 |
BarcodeEncoding.Code128 | 1D | 高密度字母數字 (物流、運輸) | 必選 (權重 Mod103) |
BarcodeEncoding.EAN13 | 1D | 零售產品識別碼,13 位數 | 必選 (Mod10) |
BarcodeEncoding.QRCode | 2D | 高容量矩陣(網址、結構化資料) | 里德-所羅門 ECC |
BarcodeEncoding.Code39 | 1D | 字母數字 (國防、汽車) | 可選 (Mod43) |
BarcodeEncoding.UPCA | 1D | 北美零售,12 位數 | 必選 (Mod10) |
BarcodeEncoding.DataMatrix | 2D | 緊湊型矩陣(電子、製藥) | 里德-所羅門 ECC |
BarcodeEncoding.PDF417 | 2D | 堆疊 (身分證、交通票券) | 里德-所羅門 ECC |
除了速度之外,限制格式集還起到驗證閘門的作用:任何未列出的符號系統所屬的BARCODE,即使實際存在於圖像中,也會被排除在結果之外。
輸入
一個符合 Code128 規範的運送標籤(成功路徑),以及一個不符合"僅限 Code128"限制的 QR 碼(失敗路徑)。
shipping-label.png(成功路徑 — Code128 符合約束條件)
qr-format-mismatch.png(失敗路徑 — QR 碼因僅支援 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
輸出
成功路徑
運送標籤的值為 SHIP-2024-00438。 受限讀取模式能立即識別出該內容,因為 Code128 正是篩選器所預期的格式;而廣泛讀取模式則確認了所有格式皆呈現相同結果。
失敗路徑
受限讀取產生的空結果是一種驗證訊號,而非錯誤; 將差異記錄下來以供審查。
對於混合多種 BarCode 類型的流程(例如,包含 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
}
每個返回的 BarcodeResult.BarcodeType 皆標示已解碼的格式,以便進行後續路由。
哪些條碼符號支援校驗和驗證?
並非所有BarCode格式都以相同方式使用校驗和。 下表將常見符號與其錯誤檢測特性進行對應,據此可決定針對各格式應如何設定 ConfidenceThreshold 與 RemoveFalsePositive 的嚴格程度:
| 符號系統 | 校驗碼類型 | 必須? | 建議 |
|---|---|---|---|
| EAN-13 / EAN-8 | Mod10 | 是的 | 預設設定即可;始終強制執行校驗和 |
| UPC-A / UPC-E | Mod10 | 是的 | 預設設定即可;校驗位元組將於寫入時自動修正 |
| Code128 | 加權 Mod103 | 是的 | 預設設定即可;須依規格要求執行 |
| Code39 | Mod43 | 可選 | 將 ConfidenceThreshold 調高至 0.8+ 並啟用 RemoveFalsePositive |
| Codabar | Mod16 | 可選 | 與 Code39 相同;以信心分數作為品質門檻 |
| ITF | Mod10 | 可選 | 針對交錯格式啟用 RemoveFalsePositive |
| QRCode / DataMatrix | 里德-所羅門 ECC | 始終 | 結構性錯誤修正;無需額外設定 |
| PDF417 | 里德-所羅門 ECC | 始終 | 與 QR 碼/DataMatrix 相同;具備內建的錯誤校正功能 |
對於 QR、DataMatrix 和 PDF417 等 2D 符碼,錯誤校正功能已整合至編碼結構中。 這些格式能夠在部分損毀的情況下進行復原,且無需依賴簡單的校驗位。 在機器學習檢測階段,ConfidenceThreshold 仍適用,而解碼步驟則能利用該符碼系統內建的冗餘機制。
既然已理解這兩種技術,讓我們將它們結合成一個可直接投入生產的驗證模式。
如何將校驗和與格式限制結合使用?
此生產就緒型態會將 ConfidenceThreshold 及 Speed 設定為單一 BarcodeReaderOptions 物件。 這些機制共同構成了一道分層防線:格式限制縮小了搜尋範圍,校驗和驗證確保資料完整性,信心閾值過濾邊緣解碼結果,而誤報移除機制則增加了第二道驗證關卡。
輸入
從用作成功路徑的 pos-scans/ 目錄中掃描三個 BARCODE:兩個 EAN-13 和一個 UPC-A。 若使用 Code128 倉儲貨架標籤作為失敗路徑,EAN-13/UPC-A 驗證機制將拒絕該標籤並記錄 REJECT 錯誤訊息。
pos-scan-1.png (成功)
pos-scan-2.png (成功)
pos-scan-3.png (成功)
warehouse-rack.png(失敗 — Code128 被拒絕)
: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
輸出
成功路徑
這三張 POS 掃描圖像均已通過審核。 讀取器傳回的值為 4006381333931 及 012345678905。 每個都與 EAN13 匹配 | UPCA | UPCE` 篩選器,具有有效的 Mod10 校驗和,且信心度高於 0.8。
失敗路徑
將 MinScanLines 設定為 3,會增加一維BARCODE被視為有效的所需最小匹配掃描線數; 預設值為 2。提高此數值可降低因雜訊掃描線導致的虛假讀取風險,但可能會導致過細或部分受損的 BARCODE 未能被讀取。 在零售 POS 環境中,若使用清晰印製的標籤,設定值 3 是一個保守的選擇,既能強化驗證機制,又不影響處理量。
讀取後的 BarcodeType 斷言屬於深度防禦機制:ExpectBarcodeTypes 已進行過濾,但明確的檢查能記錄意圖,並在不產生執行時成本的情況下偵測設定偏移。若需進行速度調校,ReadingSpeed.Faster 適用於乾淨的機器列印標籤; Detailed 和 ExtremeDetail 能夠修復受損或光線不足的 BARCODE,但代價是掃描時間較長。
接下來我該怎麼做?
本文探討了 IronBarcode 的隱式校驗和驗證模型、用於格式受限讀取的 BarcodeEncoding 旗標枚舉,以及結合 RemoveFalsePositive 及 MinScanLines 作為分層品質檢查點的複合驗證模式。
如需進一步閱讀,請參考以下資源:
- IronBarcode 教學 — BarCode 讀取指南,提供端到端的讀取操作流程。
- 詳述
RemoveFalsePositive機制中的誤報預防措施。 - 用於調校基於機器學習的偵測功能的信心閾值範例。
BarcodeResult屬性參考的輸出資料格式。- 影像校正教學:適用於提升解碼精度的濾鏡。
- 請參閱 BarcodeReaderOptions API 參考文件以獲取完整的設定文件。
- 請參閱 BarcodeEncoding API 參考文件,以查看完整支援的條碼符號清單。
常見問題
什麼是條碼校驗和驗證?
條碼校驗和驗證是一個通過將計算得出的校驗和與條碼中編碼的值進行比對來確保條碼數據準確的過程。這有助於檢測掃描過程中的錯誤。
IronBarcode如何處理校驗和驗證?
IronBarcode通過計算條碼資料的校驗和並將其與編碼的校驗和進行對比,從而隱式處理校驗和驗證,確保在掃描過程中的數據完整性。
什麼是BarcodeEncoding過濾器?
在IronBarcode中的BarcodeEncoding過濾器使您可以指定在掃描過程中讀取或忽略哪些條碼格式,從而能夠更精確和高效的條碼處理,專注於特定的條碼類型。
IronBarcode能執行結合的驗證嗎?
是的,IronBarcode 能通過在掃描過程中檢查條碼的校驗和及格式,進行結合驗證,確保僅處理有效且格式正確的條碼。
是否可以在C#中使用IronBarcode按格式限制條碼讀取?
是的,IronBarcode 允許您通過指定要包含或排除的格式來限制條碼讀取,確保您的應用程序僅處理相關的條碼類型。
格式感知讀取在條碼處理中為什麼重要?
格式感知讀取很重要,因為它使得應用程序能夠僅處理特定類型的條碼,通過忽略無關或不支持的條碼格式來提高速度和準確性。
如何在IronBarcode中實現格式感知讀取?
在IronBarcode中實施格式感知讀取,使用BarcodeEncoding過濾器指定您希望讀取的條碼格式。可以通過該程式庫的API來實現,這允許精確地控制條碼掃描需求。
使用IronBarcode進行條碼驗證有什麼好處?
IronBarcode為條碼驗證提供幾大好處,包括健壯的校驗和驗證、格式感知讀取能力、能夠處理多種條碼標準,確保條碼處理高度準確且靈活。
將IronBarcode實現於專案中需要什麼程式設計技能?
基本的C#程式設計知識足以將IronBarcode實現於專案中,因為它提供了簡單的方法和全面的文檔來指導開發者。
IronBarcode適合於小型專案和大型企業應用嗎?
IronBarcode設計為可擴展且多功能,使其適合小型專案和需要強大條碼解決方案的大型企業應用。

