如何在C#中驗證QR Code校驗和及應用容錯機制
處理實際輸入的QR Code流程,包括印刷標籤、相機擷取或掃描文件,將遇到損壞無法解碼的符號,及通過校驗和但無法經商業驗證的結果。
里德-所羅門錯誤更正在解碼時自動處理物理損壞問題。 如果符號無法恢復,則結果集為空而非部分結果。 應用層驗證是獨立的,包括在進一步處理之前檢查解碼值是否為非空、符合期望格式或包含有效的URI。
此操作指南說明如何使用IronQR程式庫驗證QR Code校驗和及應用容錯檢查。
快速入門:驗證QR Code校驗和
讀取QR code並檢查解碼是否成功:非空結果表示里德-所羅門校驗和通過。
-
使用NuGet套件管理器安裝https://www.nuget.org/packages/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 code校驗和驗證
- 使用
QrImageInput載入影像 - 呼叫
QrReader.Read解碼影像並自動執行里德-所羅門驗證 - 檢查結果集合以確認解碼成功,因為空集合意味著失敗
- 在將解碼值傳遞至下游之前,根據應用需求驗證解碼值
驗證QR Code校驗和
QR Code使用里德-所羅門錯誤更正來檢測並修復編碼資料的損壞。 更正級別(低為7%,中為15%,隔離為25%或高為30%)決定了可以失去並仍能恢復的碼字百分比。
在讀取方面,校驗和驗證在解碼時內部執行。 QrResult類別不公開信心水準屬性; 如果結果存在於集合中,則表示校驗和驗證通過。 若解碼失敗,集合為空。
輸入
中錯誤更正生成的QR Code產品標籤編碼https://ironsoftware.com/,代表一個可能在運輸中被觸摸或輕微刮傷的標籤。
: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(AnyBitmap.FromFile("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(AnyBitmap.FromFile("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 Code。 高級別可恢復最多30%資料丟失,但符號較大。
在QR Code讀取中處理格式感知
IronQR支持三種QR編碼格式:標準QR、Micro QR和矩形Micro QR。 掃描器在讀取時自動偵測格式。 掃描後,QrResult.QrType欄位以枚舉值形式提供已偵測的格式。
對於PDFs,使用QrImageInput。 掃描模式決定了速度與準確性之間的平衡:OnlyBasicScan則完全跳過ML以獲得高品質之預處理影像。
輸入
一個是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(AnyBitmap.FromFile("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(AnyBitmap.FromFile("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 = AnyBitmap.FromFile("camera-capture.jpg")
Dim fastResults = reader.Read(New QrImageInput(bitmap, QrScanMode.OnlyDetectionModel))
輸出
終端機顯示產品標籤的檢測格式、解碼值、解析的URI及角數,接著是相機擷取的快速掃描結果數。
QrType欄位對於應用程式需要特定格式時很有幫助。 例如,倉庫系統只產生標準QR Code,可以過濾出意外的Micro QR或矩形Micro QR偵測,這可能表示雜訊或無關的標籤。 每種格式都有不同的容量特徵:標準QR支援最多7,089個數字字元,Micro QR最多35,矩形Micro QR為有限標籤空間提供矩形形式。
將空值檢查應用於QR Code結果
QrReader.Read若未發現任何QR code,則返回空集合; 它永不返回null。 然而,單個結果屬性仍然需要進行驗證。 例如,如果解碼的字串不是有效的URI,Url將返回null。
堅固的驗證模式在將資料傳遞到其他系統之前檢查三個方面:集合計數、值的完整性和型別或URI的有效性。
輸入
一張白色空白圖像,沒有QR code,代表在混合批次文件中的一個沒有可機讀標籤的頁面。
:path=/static-assets/qr/content-code-examples/how-to/checksum-and-fault-tolerance/null-checking-validator.cs
using IronQr;
using IronQr.Enum;
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(AnyBitmap.FromFile(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 IronQr.Enum
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(AnyBitmap.FromFile(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 code,因此集合為空,無資料可進一步處理。
驗證器返回一個空列表(從不為null),消除了在呼叫處進行空值檢查的必要性。可選的expectedFormat參數作為格式門,讓呼叫程式僅接收符合期望格式型別的結果。 Url屬性使用空條件運算符安全處理URI和非URI的有效載荷。
對於非同步工作流程,將相同的驗證模式應用於ReadAsync:等待呼叫並對結果集合使用相同的檢查。
進一步閱讀
- 錯誤更正等級:寫入時的彈性與更正等級配置。
- 讀取QR codes操作指南:輸入格式選項及讀取模式。
- QrResult API參考:完整屬性介面。
- 高級掃描範例:掃描模式配置。
查看授權選項以便準備投入生產。
點此下載完整的ChecksumFaultToleranceTest控制臺應用專案。
常見問題
在C#中驗證QR Code校驗和的目的是什麼?
在C#中驗證QR Code校驗和確保資料完整性,通過驗證QR Code中編碼的資料是準確的且在傳輸或掃描過程中沒有被破壞。IronQR可以通過提供可靠的校驗和驗證來協助此過程。
IronQR如何處理QR Code格式檢測?
IronQR提供了強大的功能來檢測各種QR Code格式,確保與廣泛的QR Code標準相容。此功能幫助開發者在其C#應用程式中有效地處理QR Code。
Reed-Solomon錯誤校正在QR Code驗證中扮演什麼角色?
Reed-Solomon錯誤校正是一種用於QR Code的技術,用來修正掃描過程中發生的錯誤。IronQR利用此技術來增強容錯能力,使其能夠即使在某些扭曲或損壞的情況下仍能準確地讀取和驗證QR Code。
IronQR在處理QR Code時能否應用空值安全模式?
是的,IronQR可以應用空值安全模式,這有助於防止在處理QR Code資料時出現空值引用錯誤。這確保您的應用程式能更可靠地高效處理QR Code。
為什麼容錯能力在QR Code處理中很重要?
容錯能力至關重要,因為它允許QR Code處理系統在不失敗的情況下處理錯誤和不一致性。IronQR的容錯功能確保即使是部分損壞或遮擋的QR Code也能得到準確的讀取。
使用IronQR進行C#中QR Code驗證有哪些好處?
IronQR為QR Code驗證提供了多項好處,包括高精確度、對多種QR Code格式的支持以及內建的錯誤校正機制,使其成為C#開發者處理QR Code的理想選擇。
IronQR如何增強QR Code讀取的準確性?
IronQR通過利用先進的算法來檢測和解碼QR Code,以及應用Reed-Solomon等錯誤校正方法來處理掃描過程中的資料損壞,提高了讀取準確性。

