C#でQRコードのチェックサムを検証し、読み取りの耐障害性を高める方法
印刷ラベル、カメラで撮影した画像、スキャンした文書などを処理するQRコード読み取りパイプラインでは、損傷が大きくデコードできないシンボルや、チェックサム検証には通っても業務上の要件を満たさない結果が発生します。
リード・ソロモン誤り訂正は、物理的な損傷に起因するデータの誤りをデコード時に自動で訂正します。シンボルを復元できなければ、結果コレクションは空になり、部分的な結果は返りません。アプリケーション側では別途、後続処理に進む前に、デコードした値が空でないか、想定した形式に一致するか、有効なURIを含むかなどを確認します。
このガイドでは、IronQRライブラリを使ってQRコードのチェックサムを検証し、読み取りの耐障害性を高めるために結果を確認する方法を説明します。
クイックスタート: QRコードのチェックサムを検証するQRコードを読み取り、デコードに成功したかを確認します。結果コレクションに要素があれば、リード・ソロモン方式のチェックサム検証に通過しています。
-
1IronQR を 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コードチェックサム検証用のIronQR C#ライブラリをダウンロード
QrImageInputで画像を読み込むQrReader.Readを呼び出して画像をデコードし、自動でリード・ソロモン方式の検証を行う- 結果コレクションを確認する(空の場合はデコード失敗)
- デコードした値がアプリケーションの要件を満たすことを確認してから、後続処理に渡す
QRコードのチェックサムの検証
QRコードはリード・ソロモン誤り訂正を使って、エンコードしたデータの破損を検出し、訂正します。誤り訂正レベル(Lowは7%、Mediumは15%、Quartileは25%、Highは30%)により、復元可能なコードワードの欠損割合が決まります。
チェックサムはデコード時に内部で検証されます。QrResult クラスには信頼度を示す公開プロパティがありません。コレクションに結果があれば、チェックサム検証に通過しています。デコードに失敗するとコレクションは空になります。
入力
https://ironsoftware.com/ をエンコードした、誤り訂正レベルがMediumのQRコード付き製品ラベルです。輸送中の取り扱いで軽い傷が付くこともあるラベルを想定しています。

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/ が表示されます。リード・ソロモン方式でデコードに成功し、ペイロードが欠損なく復元されたことを確認できます。

物理的な損傷への耐性を高めるには、誤り訂正レベルを上げてQRコードを生成してください。Highではシンボルが大きくなる代わりに、最大30%のデータ欠損から復元できます。
QRコード読み取り時の形式の判別
IronQRは、標準QRコード、マイクロQRコード、長方形マイクロQRコードの3つの形式に対応しています。スキャナーは読み取り時に形式を自動検出します。読み取り後、QrResult.QrType フィールドから検出した形式を列挙値として取得できます。
スキャンモードによって、速度と精度のバランスが変わります。Auto は機械学習モデルによる検出と従来のスキャンを組み合わせ、OnlyDetectionModel は機械学習モデルのみを使って処理を高速化します。OnlyBasicScan は前処理済みの高品質な画像向けで、機械学習を使いません。
入力
PNG形式の製品ラベル(左)とカメラで撮影したJPEG画像(右)を使い、2種類の一般的な入力でQRコードの形式を判別する例です。

製品ラベル(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))出力
コンソールには、製品ラベルで検出したQRコードの形式、デコードした値、解決したURI、頂点の数が順に表示されます。続いて、カメラで撮影した画像の高速スキャンで得られた結果の件数が表示されます。

アプリケーションで特定の形式を求める場合は、QrType フィールドが役立ちます。たとえば、標準QRコードだけを作成する倉庫システムでは、ノイズや無関係なラベルに由来する可能性のあるマイクロQRコードや長方形マイクロQRコードの検出結果を除外できます。格納できるデータ量は形式によって異なり、標準QRコードには最大7,089桁、マイクロQRコードには最大35桁の数字を格納できます。長方形マイクロQRコードは、スペースが限られたラベルに収まりやすい長方形の形式です。
QRコード読み取り結果のnullチェック
QRコードが見つからなかった場合、QrReader.Read は空のコレクションを返し、null は返しません。ただし、各結果のプロパティは個別に検証する必要があります。たとえば、Value は空の場合があり、デコードした文字列が有効なURIでなければ Url はnullを返します。
別のシステムにデータを渡す前に、結果コレクションの件数、値の整合性、QRコードの形式またはURIの妥当性の3点を確認します。
入力
QRコードのない真っ白な画像。これは、機械読み取り可能なラベルが付いていないページが混在する文書バッチの中の1ページを表しています。

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コードが検出されなかったため、結果コレクションは空になり、後続処理にはデータが渡りません。
有効な結果がなければ検証処理は空のリストを返します。nullは返さないため、呼び出し側でnullチェックは不要です。オプションの expectedFormat パラメータを指定すると、想定した形式に一致する結果だけが呼び出し元に返ります。Url プロパティはnull条件演算子を使い、URIを含むペイロードも含まないペイロードも安全に処理します。
非同期処理では、ReadAsync の完了を待ち、返されたコレクションを同じ方法で検証します。
関連資料
- 誤り訂正レベル: 作成時に損傷への耐性を高める誤り訂正レベルの設定。
- QRコードの読み取り方法: 入力形式オプションと読み取りパターン。
- QrResult APIリファレンス: すべてのプロパティの詳細。
- 高度なスキャン例: スキャンモードの設定。
本番環境に導入する際は、ライセンスの選択肢をご確認ください。
ChecksumFaultToleranceTestコンソールアプリの完全なプロジェクトをダウンロードできます。
よくある質問
C#でQRコードのチェックサムを検証する重要性は何ですか?
QRコードのチェックサムを検証することは、QRコードに符号化されたデータの整合性を保証するために重要です。IronQRはリード・ソロモン誤り訂正を使用して、デコード中に自動的に物理的な損傷に対処し、取得されたデータが正確で信頼できることを保証します。
IronQRではリード・ソロモン誤り訂正がどのように機能しますか?
IronQRのリード・ソロモン誤り訂正は、特定のレベルまで符号化されたデータの損傷を検出して修正します。この訂正レベルは低、中、四半期、高とすることができ、デコード中に回復できるエラーの割合を決定します。
IronQRでQRコードをデコードできない場合はどうすればよいですか?
IronQRを使用してQRコードをデコードできない場合、損傷がエラー訂正の容量を超えているためかもしれません。コードを再スキャンする、誤り訂正レベルを上げてQRコードを再生成する、または入力画像の品質を改善できるか確認してください。
IronQRは異なるQRエンコーディングフォーマットを処理できますか?
はい、IronQRは、標準QR、マイクロQR、矩形マイクロQRを含む複数のQRエンコードフォーマットをサポートしています。スキャナーは読取中にフォーマットを自動的に検出し、効率的で柔軟なQRコード処理を可能にします。
IronQRを使用して画像にQRコードが検出されない場合はどうなりますか?
IronQRを使用してQRコードが検出されなかった場合、QrReader.Readメソッドは空のコレクションを返します。これはデコードが失敗し、実行できるQRデータが見つからなかったことを示しています。
アプリケーション要件に対してQRコードデータが適切であることをどのように確認できますか?
デコード後、特定のアプリケーション要件に対してデコードされた値を検証する必要があります。例えば、期待されるフォーマットを確認するか、内容が空でなく、有効なURIに一致することを確認します。
IronQRはQRコード読取時にフォーマット認識を提供しますか?
はい、IronQRは読取時にQRコードフォーマットを検出することによりフォーマット認識を提供します。QrResultオブジェクトの一部としてフォーマットを返し、あなたのアプリケーションが特定のフォーマットを適切に処理できるようにします。
IronQRの`QrResult`クラスの役割は何ですか?
IronQRのQrResultクラスは、QRコード読取り結果を表します。デコードされた値、検出されたQRタイプ、およびオプションで値が有効なURLである場合のURIなどのプロパティを提供します。
IronQRはQRコードに対する物理的な損傷をどのように扱いますか?
IronQRはリード・ソロモン誤り訂正を使用して、デコード中にQRコードの軽微な損傷を自動的に修正し、物理的な損傷に耐性がありデータの整合性を保証します。
IronQRでQRコードを非同期に検証できますか?
はい、IronQRは非同期ワークフローをサポートしています。ReadAsyncを使用して、非ブロッキングのQRコード読取りを行いながら、結果に対して同様の検証パターンを適用することができます。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。