QRコードのチェックサムを検証し、C#で耐障害性を適用する方法
印刷されたラベル、カメラで撮影した画像、スキャンした文書など、現実世界の入力を処理するQRコード処理パイプラインでは、デコードするには損傷がひどすぎるシンボルや、チェックサムは合格するもののビジネス上の検証に失敗する結果に遭遇する可能性があります。
リード・ソロモン誤り訂正は、復号中に物理的な損傷を自動的に修復します。 シンボルを復元できない場合、結果コレクションは部分的なものではなく、空になります。 アプリケーションレベルの検証は別個のものであり、デコードされた値が空でないこと、想定される形式と一致していること、または有効なURIを含んでいることを、後続の処理の前に確認するものです。
このハウツーでは、 IronQRライブラリを使用してQRコードのチェックサムを検証し、フォールトトレランスチェックを適用する方法を説明します。
クイックスタート: QRコードのチェックサムを検証する
QRコードを読み取り、デコードが成功したかどうかを確認します。結果が空でない場合は、リード・ソロモンチェックサムが合格したことを意味します。
-
IronQR をNuGetパッケージマネージャでインストール
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ステップ)
- QRコードチェックサム検証用のIronQR C#ライブラリをダウンロード
QrImageInputで画像を読み込むQrReader.Readを呼び出して画像をデコードし、リード・ソロモン検証を自動的に実行します。- 結果コレクションを確認してデコードが成功したことを確認してください。コレクションが空の場合は失敗を意味します。
- デコードされた値をアプリケーション要件と照合してから、下流に渡してください。
QRコードのチェックサムの検証
QRコードはリードソロモン誤り訂正を使用して、符号化データの損傷を検出し、修復します。 補正レベル(低:7%、中:15%、四分位:25%、高:30%)は、失われても回復可能なコードワードの割合を決定します。
読み取り側では、デコード中に内部的にチェックサム検証が実行されます。 QrResultクラスは信頼度プロパティを公開していません。 結果がコレクション内に存在する場合、チェックサムは合格です。 デコードに失敗した場合、コレクションは空になります。
入力
中程度の誤り訂正機能を使用して生成された、https://ironsoftware.com/をエンコードしたQRコード製品ラベル。輸送中に取り扱われたり、軽く傷がついたりした可能性のあるラベルを表しています。
: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、長方形マイクロQRの3種類のQRコードエンコード形式をサポートしています。 スキャナーは読み取り時にフォーマットを自動的に検出します。 スキャン後、QrResult.QrTypeフィールドには、検出されたフォーマットが列挙型値として返されます。
PDFについては、QrPdfInputを使用してください。 スキャンモードは、速度と精度のバランスを決定します。OnlyBasicScanは高品質な前処理済み画像を得るためにMLを完全に省略します。
入力
PNG形式の製品ラベル(左)とJPEG形式のカメラ画像(右)は、2つの一般的な入力形式におけるフォーマット認識読み取りの例を示すものです。
製品ラベル(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コードのみを生成する倉庫システムであれば、ノイズや無関係なラベルを示している可能性のある、予期せぬマイクロQRコードや長方形マイクロQRコードの検出をフィルタリングすることができます。 各フォーマットにはそれぞれ異なる容量特性があります。標準QRコードは最大7,089文字、マイクロQRコードは最大35文字まで対応し、長方形マイクロQRコードは限られたラベルスペースに適した長方形の形状を提供します。
QRコードの結果にヌルチェックを適用する
QrReader.Read は、QRコードが見つからない場合、空のコレクションを返します; nullは決して返されません。 しかし、個々の結果特性については、依然として検証が必要である。 たとえば、Value は空になる場合があり、デコードされた文字列が有効な URI でない場合、Url は null を返します。
堅牢な検証パターンでは、データを別のシステムに渡す前に、コレクション数、値の整合性、および型またはURIの有効性という3つの側面をチェックします。
入力
QRコードのない真っ白な画像。これは、機械読み取り可能なラベルが付いていないページが混在する文書バッチの中の1ページを表しています。
: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 コンソールアプリのプロジェクト全体をダウンロードするには、こちらをクリックしてください。

