如何在 C# 中驗證 QR 碼校驗和並實施容錯機制
處理實體輸入(包括印刷標籤、相機拍攝影像或掃描文件)的 QR 碼處理流程,可能會遇到損毀過於嚴重而無法解碼的符號,以及通過校驗碼檢查但未能通過業務驗證的結果。
里德-所羅門(Reed-Solomon)錯誤校正技術能在解碼過程中自動處理物理損壞。 若無法復原某個符號,結果集合將為空,而非包含部分結果。 應用層級的驗證是獨立進行的,包含在進一步處理前,檢查解碼後的值是否不為空、是否符合預期格式,或是否包含有效的 URI。
本操作指南說明如何使用 IronQR程式庫驗證 QR 碼校驗和,並執行容錯檢查。
快速入門:驗證 QR 碼校驗和
讀取 QR 碼並檢查解碼是否成功:若結果不為空,表示通過了里德-所羅門校驗。
-
using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronQR
PM > Install-Package IronQR -
請複製並執行此程式碼片段。
using IronQr; using IronSoftware.Drawing; var reader = new QrReader(); IEnumerable<QrResult> results = reader.Read(new QrImageInput("label.png")); if (!results.Any()) { Console.WriteLine("No QR code detected or decoding failed."); return; } Console.WriteLine(results.First().Value); -
部署至您的生產環境進行測試
立即透過免費試用,在您的專案中開始使用 IronQR
簡化工作流程(5 個步驟)
- 下載 IronQR C# 程式庫,用於 QR 碼校驗碼驗證
- 使用
QrImageInput載入圖片 - 呼叫
QrReader.Read來解碼圖像,並自動執行里德-所羅門驗證 - 請檢查結果集合以確認解碼是否成功,若集合為空則表示失敗
- 在將解碼後的值傳遞至下游之前,請先根據應用程式需求進行驗證
驗證 QR 碼校驗和
QR 碼採用里德-所羅門(Reed-Solomon)錯誤校正機制,用以偵測並修復編碼資料的損壞。 修正等級(低級 7%、中級 15%、四分位 25% 或高級 30%)決定了可遺失且仍能恢復的代碼詞百分比。
在讀取方面,校驗碼驗證會在解碼過程中於內部執行。 QrResult 類別未公開信心屬性; 若集合中存在結果,則傳回該結果的校驗和。 若解碼失敗,則集合為空。
輸入
一個編碼為 https://ironsoftware.com/ 的 QR 碼產品標籤,採用 Medium 錯誤校正機制生成,代表該標籤在運輸過程中可能曾被觸碰或輕微刮傷。
:path=/static-assets/qr/content-code-examples/how-to/checksum-and-fault-tolerance/checksum-validation.cs
using IronQr;
using IronSoftware.Drawing;
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput("damaged-label.png"));
// Reed-Solomon decoding is pass/fail — presence in results means valid checksum
if (!results.Any())
{
// Decoding failed entirely — damage exceeded the error correction capacity
Console.WriteLine("QR code could not be decoded. Consider re-scanning or using a higher error correction level at generation time.");
return;
}
foreach (QrResult result in results)
{
// Decoded successfully — validate the content matches expected format
if (string.IsNullOrWhiteSpace(result.Value))
{
Console.WriteLine("QR decoded but produced an empty value.");
continue;
}
Console.WriteLine($"Valid QR: {result.Value}");
}
Imports IronQr
Imports IronSoftware.Drawing
Dim reader As New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput("damaged-label.png"))
' Reed-Solomon decoding is pass/fail — presence in results means valid checksum
If Not results.Any() Then
' Decoding failed entirely — damage exceeded the error correction capacity
Console.WriteLine("QR code could not be decoded. Consider re-scanning or using a higher error correction level at generation time.")
Return
End If
For Each result As QrResult In results
' Decoded successfully — validate the content matches expected format
If String.IsNullOrWhiteSpace(result.Value) Then
Console.WriteLine("QR decoded but produced an empty value.")
Continue For
End If
Console.WriteLine($"Valid QR: {result.Value}")
Next
輸出
主控台顯示解碼後的值 https://ironsoftware.com/,確認里德-所羅門解碼成功,且有效載荷已完整恢復。
為增強對物理損壞的抗性,請生成具有更高錯誤校正等級的 QR 碼。 高階模式可恢復多達 30% 的資料損失,但代價是符號會變大。
QR 碼讀取中的格式辨識處理
IronQR 支援三種 QR 編碼格式:標準 QR、Micro QR 以及矩形 Micro QR。 掃描器會在讀取時自動偵測格式。 掃描完成後,QrResult.QrType 欄位會以枚舉值的形式提供偵測到的格式。
針對 PDF 檔案,請使用 QrPdfInput 取代 QrImageInput。 掃描模式決定了速度與精準度的平衡:Auto 結合機器學習偵測與傳統掃描;OnlyDetectionModel 僅使用機器學習模型以加快處理速度;而 OnlyBasicScan 則完全跳過機器學習,適用於高品質的預處理圖像。
輸入
左側為 PNG 產品標籤,右側為 JPEG 相機拍攝畫面,展示針對兩種常見輸入類型的格式感知讀取功能。
產品標籤 (PNG)
相機擷取 (JPEG)
:path=/static-assets/qr/content-code-examples/how-to/checksum-and-fault-tolerance/format-awareness.cs
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
// Read from an image file with ML + classic scan (default)
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput("product-label.png"));
foreach (QrResult result in results)
{
// Inspect the detected QR format
Console.WriteLine($"Format: {result.QrType}"); // QRCode, MicroQRCode, or RMQRCode
Console.WriteLine($"Value: {result.Value}");
// Url is non-null only if Value is a valid URI
if (result.Url != null)
{
Console.WriteLine($"URI: {result.Url.AbsoluteUri}");
}
// Corner coordinates for positional context
Console.WriteLine($"Corners: {result.Points.Length} points detected");
}
// Read from a bitmap with ML-only mode for faster throughput
var bitmap = AnyBitmap.FromFile("camera-capture.jpg");
var fastResults = reader.Read(new QrImageInput(bitmap, QrScanMode.OnlyDetectionModel));
Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
' Read from an image file with ML + classic scan (default)
Dim reader As New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput("product-label.png"))
For Each result As QrResult In results
' Inspect the detected QR format
Console.WriteLine($"Format: {result.QrType}") ' QRCode, MicroQRCode, or RMQRCode
Console.WriteLine($"Value: {result.Value}")
' Url is non-null only if Value is a valid URI
If result.Url IsNot Nothing Then
Console.WriteLine($"URI: {result.Url.AbsoluteUri}")
End If
' Corner coordinates for positional context
Console.WriteLine($"Corners: {result.Points.Length} points detected")
Next
' Read from a bitmap with ML-only mode for faster throughput
Dim bitmap As AnyBitmap = AnyBitmap.FromFile("camera-capture.jpg")
Dim fastResults = reader.Read(New QrImageInput(bitmap, QrScanMode.OnlyDetectionModel))
輸出
主控台會顯示產品標籤的偵測格式、解碼值、解析後的 URI 以及邊角計數,隨後顯示相機擷取影像的快速掃描結果計數。
當應用程式需要特定格式時,QrType 欄位會很有幫助。 舉例來說,僅產生標準 QR 碼的倉儲系統,可過濾掉意外偵測到的 Micro QR 或矩形 Micro QR,這些情況可能表示存在雜訊或無關的標籤。 每種格式皆具備獨特的容量特性:標準 QR 碼最多可容納 7,089 個數字字元,Micro QR 最多 35 個,而矩形 Micro QR 則提供矩形外觀,適用於標籤空間有限的情境。
對 QR 碼結果進行空值檢查
QrReader.Read 若未找到任何 QR 碼,則會傳回一個空集合; 它永遠不會返回 null。 然而,個別結果屬性仍需進行驗證。 例如,若解碼後的字串不是有效的 URI,Value 可能會為空,而 Url 則會傳回 null。
在將資料傳遞至其他系統之前,強健的驗證模式會檢查三個方面:集合數量、值的一致性,以及類型或 URI 的有效性。
輸入
一張沒有 QR 碼的空白白色圖片,代表混合批次中的一頁文件,該批次中部分頁面未附有機器可讀的標籤。
:path=/static-assets/qr/content-code-examples/how-to/checksum-and-fault-tolerance/null-checking-validator.cs
using IronQr;
using IronSoftware.Drawing;
using System.Collections.Generic;
using System.Linq;
public static class QrValidator
{
public static List<QrResult> GetValidResults(
string imagePath,
QrEncoding? expectedFormat = null)
{
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(imagePath));
// Guard: no QR codes detected
if (!results.Any())
return new List<QrResult>();
return results
.Where(r => !string.IsNullOrWhiteSpace(r.Value))
.Where(r => expectedFormat == null || r.QrType == expectedFormat)
.ToList();
}
}
// Usage — only accept standard QR codes with non-empty values
var validated = QrValidator.GetValidResults(
"shipping-manifest.png",
expectedFormat: QrEncoding.QRCode);
if (validated.Count == 0)
{
Console.WriteLine("No valid QR codes found for processing.");
return;
}
foreach (var qr in validated)
{
// Safe for downstream: value is non-empty, format is verified
SendToInventoryApi(qr.Value, qr.Url?.AbsoluteUri);
}
Imports IronQr
Imports IronSoftware.Drawing
Imports System.Collections.Generic
Imports System.Linq
Public Module QrValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedFormat As QrEncoding? = Nothing) As List(Of QrResult)
Dim reader As New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(imagePath))
' Guard: no QR codes detected
If Not results.Any() Then
Return New List(Of QrResult)()
End If
Return results _
.Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)) _
.Where(Function(r) expectedFormat Is Nothing OrElse r.QrType = expectedFormat) _
.ToList()
End Function
End Module
' Usage — only accept standard QR codes with non-empty values
Dim validated = QrValidator.GetValidResults(
"shipping-manifest.png",
expectedFormat:=QrEncoding.QRCode)
If validated.Count = 0 Then
Console.WriteLine("No valid QR codes found for processing.")
Return
End If
For Each qr In validated
' Safe for downstream: value is non-empty, format is verified
SendToInventoryApi(qr.Value, qr.Url?.AbsoluteUri)
Next qr
輸出
主控台顯示驗證器的空結果回應:未偵測到任何 QR 碼,因此集合為空,且沒有資料會進入後續處理流程。
驗證器會傳回一個空清單(絕不會是 null),因此無需在呼叫處進行 null 檢查。可選的 expectedFormat 參數充當格式閘門,確保呼叫程式碼僅接收符合預期格式類型的結果。 Url 屬性使用 null 條件運算子,以安全地處理 URI 與非 URI 載入內容。
針對非同步工作流程,請將相同的驗證模式套用至 ReadAsync:等待呼叫完成,並對結果集合執行相同的檢查。
延伸閱讀
- 錯誤修正層級:寫入時容錯能力與修正層級設定。
- 讀取 QR 碼操作指南:輸入格式選項與讀取模式。
- QrResult API 參考:完整的屬性清單。
- 進階掃描範例:掃描模式設定。
準備投入生產環境時,請查看授權選項。
點擊此處下載完整的 ChecksumFaultToleranceTest 控制台應用程式專案。
常見問題
在 C# 中驗證 QR 碼校驗和的目的是什麼?
在 C# 中驗證 QR 碼校驗和,可透過確認 QR 碼中編碼的資料是否正確,以及在傳輸或掃描過程中是否未遭損毀,來確保資料完整性。IronQR 可透過提供可靠的校驗和驗證功能,協助完成此流程。
IronQR 是如何處理 QR 碼格式偵測的?
IronQR 提供強大的功能,可偵測各種 QR 碼格式,確保與廣泛的 QR 碼標準相容。此功能有助於開發人員在其 C# 應用程式中高效處理 QR 碼。
里德-所羅門(Reed-Solomon)錯誤校正機制在 QR 碼驗證中扮演什麼角色?
里德-所羅門(Reed-Solomon)錯誤校正是一種應用於 QR 碼的技術,用於修正掃描過程中發生的錯誤。IronQR 運用此技術來增強容錯能力,使其即使面對一定程度的變形或損壞,仍能準確讀取並驗證 QR 碼。
IronQR 在處理 QR 碼時能否應用空值安全模式?
是的,IronQR 支援空值安全模式,有助於在處理 QR 碼資料時防止空值引用錯誤。這能確保您的應用程式能更可靠且高效地處理 QR 碼。
為何容錯能力在 QR 碼處理中如此重要?
容錯能力至關重要,因為它能讓 QR 碼處理系統在不發生故障的情況下處理錯誤與差異。IronQR 的容錯能力確保即使部分受損或模糊的 QR 碼也能被準確讀取。
在 C# 中使用 IronQR 進行 QR 碼驗證有哪些好處?
IronQR 在 QR 碼驗證方面具備多項優勢,包括高準確度、支援多種 QR 碼格式,以及內建的錯誤修正機制,使其成為使用 C# 處理 QR 碼的開發人員的理想選擇。
IronQR 是如何提升 QR 碼讀取精度的?
IronQR 透過運用先進演算法來偵測與解碼 QR 碼,並採用 Reed-Solomon 等錯誤校正方法來處理掃描過程中的資料損毀,從而提升讀取準確性。

