如何在 C# 中驗證 QR 碼校驗和並應用容錯機制

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

處理現實世界輸入(包括列印標籤、相機拍攝的影像或掃描的文件)的二維碼管道會遇到損壞嚴重而無法解碼的符號,以及透過校驗和但未通過業務驗證的結果。

里德-所羅門糾錯技術能夠自動解決解碼過程中的物理損壞問題。 如果無法恢復某個符號,則結果集為空而不是部分結果。 應用層驗證是獨立的,它涉及在進一步處理之前檢查解碼後的值是否為非空、是否符合預期格式或是否包含有效的 URI。

本文介紹如何使用IronQR函式庫驗證二維碼校驗和並套用容錯檢查。

快速入門:驗證 QR 碼校驗和

讀取二維碼並檢查解碼是否成功:非空結果表示里德-所羅門校驗和通過。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronQR

    PM > Install-Package IronQR
  2. 複製並運行這段程式碼。

    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);
  3. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronQR

    arrow pointer

驗證二維碼校驗和

QR 碼採用里德-所羅門(Reed-Solomon)錯誤校正演算法,用於偵測並修復編碼資料的損壞。 校正程度(低為 7%,中為 15%,四分位數為 25%,高為 30%)決定了可以遺失但仍能恢復的碼字百分比。

在讀取方面,校驗和驗證在解碼過程中內部運作。 QrResult 類別沒有公開 confidence 屬性; 如果集合中存在結果,則校驗和通過。 如果解碼失敗,則集合為空。

輸入

一個編碼為 https://ironsoftware.com/ 的 QR 碼產品標籤,採用 Medium 錯誤校正機制生成,代表該標籤在運輸過程中可能曾被觸碰或輕微刮傷。

二維碼編碼 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("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
$vbLabelText   $csharpLabel

輸出

主控台顯示解碼後的值 https://ironsoftware.com/,確認里德-所羅門解碼成功,且有效載荷已完整恢復。

終端輸出顯示解碼的二維碼:https://ironsoftware.com

為了提高抗物理損壞能力,請產生具有更高糾錯等級的二維碼。 進階版本可以恢復高達 30% 的資料遺失,但代價是符號更大。


處理二維碼讀取中的格式感知

IronQR支援三種 QR 編碼格式:標準 QR、Micro QR 和矩形 Micro QR。 掃描器在讀取過程中會自動偵測格式。 掃描完成後,QrResult.QrType 欄位會以枚舉值的形式提供偵測到的格式。

針對 PDF 檔案,請使用 QrPdfInput 取代 QrImageInput。 掃描模式決定了速度與精準度的平衡:Auto 結合機器學習偵測與傳統掃描,OnlyDetectionModel 僅使用 ML 模型以加快處理速度,而 OnlyBasicScan 則完全跳過 ML,適用於高品質的預處理圖像。

輸入

PNG 產品標籤(左)和 JPEG 相機拍攝影像(右),展示了對兩種常見輸入類型進行格式感知讀取的功能。

product-label.png QR code used as input for format-aware reading
camera-capture.jpg JPEG QR code simulating a camera capture
: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))
$vbLabelText   $csharpLabel

輸出

控制台顯示產品標籤的偵測到的格式、解碼值、解析的 URI 和角數,然後顯示相機擷取的快速掃描結果計數。

終端輸出顯示:格式:QRCode,值:https://ironsoftware.com/product,URI,以及偵測到的角落:4 個。

當應用程式需要特定格式時,QrType 欄位會很有幫助。 例如,一個只產生標準二維碼的倉庫系統可以過濾掉意外的微型二維碼或矩形微型二維碼檢測結果,這些結果可能表示雜訊或無關標籤。 每種格式都有其獨特的容量特性:標準 QR 碼最多支援 7,089 個數字字符,Micro QR 碼最多支援 35 個字符,而矩形 Micro QR 碼則採用矩形外形,適用於標籤空間有限的情況。


對二維碼結果套用空值檢查

QrReader.Read 若未找到任何 QR 碼,則會傳回一個空集合; 它永遠不會返回 null。 但是,各個結果屬性仍需驗證。 例如,若解碼後的字串不是有效的 URI,則 Value 可能為空,而 Url 會傳回 null。

一個完善的驗證模式會在將資料傳遞給另一個系統之前檢查三個方面:集合計數、值完整性和類型或 URI 有效性。

輸入

一張沒有二維碼的空白白色影像,代表一批混合文件中的一頁,其中一些頁面沒有機器可讀標籤。

使用一張空白白色影像(不含二維碼)作為輸入進行空值檢查演示
: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
$vbLabelText   $csharpLabel

輸出

控制台顯示驗證器的空結果回應:未偵測到二維碼,因此集合為空,沒有資料繼續進行下游處理。

終端輸出顯示:未找到可處理的有效二維碼。

驗證器會傳回一個空清單(絕不會傳回 null),因此無需在呼叫處進行 null 檢查。可選的 expectedFormat 參數充當格式閘門,確保呼叫程式碼僅接收符合預期格式類型的結果。 Url 屬性使用空值條件運算子,以安全地處理 URI 與非 URI 載荷。

對於非同步工作流程,對 ReadAsync 應用相同的驗證模式:等待呼叫並對結果集合使用相同的檢查。


延伸閱讀

-錯誤修正等級:寫入時復原能力和修正等級配置。 -如何讀取二維碼:輸入格式選項和讀取模式。

準備生產時,請查看許可證選項

點擊這裡下載完整的 ChecksumFaultToleranceTest 控制台應用程式專案。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

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

還在捲動嗎?

想要快速證明? PM > Install-Package IronQR
執行範例 觀看您的 URL 變成 QR code。