在 C# 中驗證 QR Code 校驗和並套用容錯機制的方法
處理印刷標籤、相機拍攝影像或掃描文件等實際輸入時,QR Code 處理流程可能遇到嚴重損壞而無法解碼的圖碼,也可能遇到通過校驗和檢查卻不符合業務規則的結果。
解碼時,Reed-Solomon 錯誤校正會自動修復實體損壞造成的錯誤。若無法還原圖碼,結果集合會是空的,不會傳回部分結果。應用程式層級的驗證需另行執行。在進一步處理之前,請檢查解碼值是否非空、是否符合預期格式,或是否包含有效的 URI。
本指南介紹如何使用 IronQR 程式庫驗證 QR Code 校驗和,並執行容錯檢查。
快速入門:驗證 QR Code 校驗和讀取 QR Code 後,請檢查解碼是否成功。結果集合非空,表示已通過 Reed-Solomon 校驗和檢查。
-
1使用 IronQR 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
using IronQr; using IronSoftware.Drawing; var reader = new QrReader(); IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile("label.png"))); if (!results.Any()) { Console.WriteLine("No QR code detected or decoding failed."); return; } Console.WriteLine(results.First().Value);Imports IronQr Imports IronSoftware.Drawing Dim reader = New QrReader() Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("label.png"))) If Not results.Any() Then Console.WriteLine("No QR code detected or decoding failed.") Return End If Console.WriteLine(results.First().Value)Imports IronQr Imports IronSoftware.Drawing Dim reader = New QrReader() Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("label.png"))) If Not results.Any() Then Console.WriteLine("No QR code detected or decoding failed.") Return End If Console.WriteLine(results.First().Value) -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronQR,並使用 免費試用
基本工作流程(5 個步驟)
- 下載用於QR Code 校驗和驗證的IronQR C#程式庫
- 使用
QrImageInput載入圖片 - 呼叫
QrReader.Read函數解碼影像並自動執行Reed-Solomon驗證。 - 檢查結果集合以確認解碼是否成功,因為空集合表示解碼失敗。
- 在將解碼值傳遞給下游之前,請根據應用程式要求驗證解碼後的值。
驗證QR Code 校驗和
QR Code 使用 Reed-Solomon 錯誤校正偵測並修正編碼資料中的錯誤。校正等級(Low 為 7%、Medium 為 15%、Quartile 為 25%、High 為 30%)決定在仍可還原資料的情況下,最多可遺失多少比例的碼字。
讀取時,解碼程序會在內部驗證校驗和。QrResult 類別沒有提供信賴度屬性。集合中有結果就表示已通過校驗和檢查,解碼失敗則會傳回空集合。
輸入
這張產品標籤包含以 Medium 錯誤校正等級產生的 QR Code,編碼內容為 https://ironsoftware.com/,用來模擬在運送途中可能經過搬動或略有刮痕的標籤。

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}");
}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 = 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}")
NextImports IronQr
Imports IronSoftware.Drawing
Dim reader = 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/,確認 Reed-Solomon 解碼成功且完整還原了編碼資料。

若要提高對實體損壞的耐受性,請使用更高的錯誤校正等級產生 QR Code。High 等級最多可還原 30% 的遺失資料,但需要較大的圖碼。
讀取 QR Code 時辨識格式
IronQR 支援三種 QR Code 編碼格式:標準 QR、Micro QR 和 Rectangular Micro QR。掃描器會在讀取時自動偵測格式,並在 QrResult.QrType 欄位以列舉值提供結果。
掃描模式決定速度與準確度之間的取捨。Auto 結合機器學習偵測與傳統掃描。OnlyDetectionModel 只使用機器學習模型,以加快處理速度。OnlyBasicScan 完全略過機器學習,適合已完成前處理的高品質影像。
輸入
左側為 PNG 產品標籤,右側為相機拍攝的 JPEG 影像,用來示範讀取這兩種常見輸入時的格式辨識。

產品標籤(PNG格式)

相機拍攝(JPEG)
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));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))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 或 Rectangular Micro QR,因為這些結果可能來自雜訊或無關的標籤。各格式的容量和外形不同。標準 QR Code 最多可容納 7,089 個數字字元,Micro QR 最多可容納 35 個數字字元,Rectangular Micro QR 則採用長方形,適合空間有限的標籤。
對QR Code結果套用空值檢查
QrReader.Read 找不到 QR Code 時會傳回空集合,絕不傳回 null。不過,仍須驗證個別結果的屬性。例如,Value 可能為空,而解碼字串若不是有效的 URI,Url 就會傳回 null。
可靠的驗證模式檢查三個方面:集合數量、值的完整性和類型或URI的有效性,然後才將資料傳遞給其他系統。
輸入
一張沒有QR Code的空白白色影像,代表一批混合文件中的一頁,其中一些頁面沒有機器可讀標籤。

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);
}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
Public Module QrValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedFormat As QrEncoding? = Nothing) As List(Of QrResult)
Dim reader = 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 qrImports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Public Module QrValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedFormat As QrEncoding? = Nothing) As List(Of QrResult)
Dim reader = 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輸出
主控台顯示驗證器的空結果回應:未偵測到QR Code,因此集合為空,沒有資料繼續進行下游處理。
驗證器會傳回空清單而非 null,因此呼叫端無須檢查 null。選用的 expectedFormat 參數可用來篩選格式,讓呼叫端只收到符合預期格式的結果。Url 屬性使用 null 條件運算子,可安全處理 URI 和非 URI 資料。
在非同步流程中,請對 ReadAsync 採用相同的驗證方式。等待呼叫完成後,對傳回的集合執行相同的檢查。
延伸閱讀
- 錯誤校正等級:產生時的抗損能力和校正等級設定。
- 讀取 QR Code 的方法:輸入格式選項和讀取方式。
- QrResult API參考:所有屬性的說明。
- 進階掃描範例:掃描模式設定。
準備部署至正式環境時,請查看授權選項。
下載完整的ChecksumFaultToleranceTest主控台應用程式專案。
常見問題
在C#中驗證QR碼校驗和的重要性是什麼?
驗證QR碼校驗和對於確保QR碼中編碼數據的完整性至關重要。IronQR使用里德-所羅門錯誤校正自動解決解碼過程中的任何物理損壞,確保檢索到的數據準確可靠。
里德-所羅門錯誤校正在IronQR中如何運作?
IronQR的里德-所羅門錯誤校正會檢測並修復編碼數據的損壞,達到特定級別。這個校正級別可以是低、中、四分位或高,決定了解碼過程中可以恢復的錯誤百分比。
如果QR碼無法用IronQR解碼,我應該怎麼辦?
如果QR碼無法使用IronQR解碼,可能是因為損壞超過了錯誤校正容量。您可以嘗試重新掃描該碼,或者使用更高錯誤校正級別重新生成QR碼,或者檢查是否可以改善輸入圖像質量。
IronQR能處理不同的QR編碼格式嗎?
是的,IronQR支持多種QR編碼格式,包括標準QR碼、微型QR碼和長方形微型QR碼。掃描器在讀取過程中自動檢測格式,允許高效和靈活的QR碼處理。
如果使用IronQR的圖像中未檢測到QR碼,會發生什麼?
如果使用IronQR未檢測到QR碼,QrReader.Read方法會返回一個空集合。這表示解碼失敗,沒有找到可操作的QR數據。
我如何確保QR碼數據適合我的應用需求?
解碼後,您應該根據特定應用需求驗證解碼值,例如檢查期望的格式或確認內容非空且匹配有效URI。
IronQR在QR碼讀取過程中提供格式意識嗎?
是的,IronQR在讀取過程中通過檢測QR碼格式來提供格式意識。它會在QrResult對象中返回格式,允許您的應用程序適當處理特定格式。
`QrResult`類在IronQR中的作用是什麼?
QrResult類在IronQR中代表從QR碼讀取的解碼結果。它提供了類似解碼值、檢測的QR類型以及可選的URI(如果該值是有效URL)等屬性。
IronQR如何處理QR碼的物理損壞?
IronQR使用里德-所羅門錯誤校正來自動修正解碼過程中的小損壞,使其對物理損壞更具彈性並確保數據完整性。
IronQR能夠異步驗證QR碼嗎?
是的,IronQR支持異步工作流程。您可以使用ReadAsync來執行非阻塞QR碼讀取,同時在結果上應用類似的驗證模式。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。