C#バーコードスキャナー: .NETアプリケーションでバーコードとQRコードを読み取る
.NETアプリケーションでバーコードやQRコードを素早くスキャンする必要がありますか? IronBarcodeは、完璧なデジタル画像でも、挑戦的な実世界の写真でも、バーコードの読み取りを簡単で信頼できるものにします。 このガイドでは、C#でのバーコードスキャンの実装方法を実際にすぐ使える実例と共に示しています。
クイックスタート: ファイルからバーコードを即座に読み取る
この短い例は、IronBarcodeを使い始めるのがどれだけ簡単かを示しています。 コード1行で、画像ファイルからバーコードを読み取ることができ、複雑なセットアップは不要です。
最小限のワークフロー(5ステップ)
- NuGet または DLL ダウンロードから IronBarcode をインストールします。
- `BarcodeReader.Read`メソッドを使用して、任意のバーコードまたは QR コードをスキャンします。
- 1 回のスキャン、PDF、またはマルチフレーム TIFF ファイルで複数のバーコードまたは QR コードを読み取ります
- IronBarcode を有効にして、高度なフィルターを使用して不完全なスキャンや写真をデコードします
- チュートリアルプロジェクトをダウンロードしてすぐにスキャンを開始してください
どうやって.NETプロジェクトにIronBarcodeをインストールしますか?
IronBarcodeは、NuGetパッケージマネージャーまたはDLLを直接ダウンロードすることで簡単にインストールできます。 NuGetによるインストールは依存関係と更新を自動で管理するため推奨される方法です。
Install-Package BarCode
インストール後、バーコード スキャン機能にアクセスするには、C# ファイルに using IronBarCode; を追加します。 さまざまな開発環境での詳細なインストール手順については、インストールガイドを確認してください。
どうすればC#を使って最初のバーコードを読むことができますか?
IronBarcodeでバーコードを読むのに必要なのは、コード1行だけです。 ライブラリは自動的にバーコードフォーマットを検出し、すべてのエンコードされたデータを抽出します。
*IronBarcodeが瞬時に読み取れる標準のCode128バーコード*using IronBarCode;
using System;
// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");
// Check if any barcodes were detected
if (results != null && results.Count > 0)
{
// Process each barcode found in the image
foreach (BarcodeResult result in results)
{
// Extract the text value from the barcode
Console.WriteLine("Barcode detected! Value: " + result.Text);
// Additional properties available:
// result.BarcodeType - The format (Code128, QR, etc.)
// result.BinaryValue - Raw binary data if applicable
// result.Confidence - Detection confidence score
}
}
else
{
Console.WriteLine("No barcodes detected in the image.");
}
using IronBarCode;
using System;
// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");
// Check if any barcodes were detected
if (results != null && results.Count > 0)
{
// Process each barcode found in the image
foreach (BarcodeResult result in results)
{
// Extract the text value from the barcode
Console.WriteLine("Barcode detected! Value: " + result.Text);
// Additional properties available:
// result.BarcodeType - The format (Code128, QR, etc.)
// result.BinaryValue - Raw binary data if applicable
// result.Confidence - Detection confidence score
}
}
else
{
Console.WriteLine("No barcodes detected in the image.");
}
Imports IronBarCode
Imports System
' Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
Dim results As BarcodeResults = BarcodeReader.Read("GetStarted.png")
' Check if any barcodes were detected
If results IsNot Nothing AndAlso results.Count > 0 Then
' Process each barcode found in the image
For Each result As BarcodeResult In results
' Extract the text value from the barcode
Console.WriteLine("Barcode detected! Value: " & result.Text)
' Additional properties available:
' result.BarcodeType - The format (Code128, QR, etc.)
' result.BinaryValue - Raw binary data if applicable
' result.Confidence - Detection confidence score
Next
Else
Console.WriteLine("No barcodes detected in the image.")
End If
BarcodeReader.Read メソッドは、検出されたすべてのバーコードを含む BarcodeResults コレクションを返します。 各 BarcodeResult は、バーコードのテキスト値、形式タイプ、位置座標、およびバイナリ データへのアクセスを提供します。 このアプローチは、Code128、Code39、QRコード、Data Matrixコードを含む一般的なバーコードフォーマットとシームレスに動作します。
難しいまたは損傷したバーコードを読むのに役立つオプションは何ですか?
実世界でのバーコードスキャンは、しばしば不完全な画像 - 傾いた角度、悪い照明、または部分的な損傷を伴います。 IronBarcodeの高度なオプションは、これらの課題を効果的に処理します。
using IronBarCode;
// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Speed settings: Faster, Balanced, Detailed, ExtremeDetail
// ExtremeDetail performs deep analysis for challenging images
Speed = ReadingSpeed.ExtremeDetail,
// Specify expected formats to improve performance
// Use bitwise OR (|) to combine multiple formats
ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
// Maximum number of barcodes to find (0 = unlimited)
MaxParallelThreads = 4,
// Crop region for faster processing of specific areas
CropArea = null // Or specify a Rectangle
};
// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
// Process detected barcodes
foreach (var barcode in results)
{
Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
using IronBarCode;
// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Speed settings: Faster, Balanced, Detailed, ExtremeDetail
// ExtremeDetail performs deep analysis for challenging images
Speed = ReadingSpeed.ExtremeDetail,
// Specify expected formats to improve performance
// Use bitwise OR (|) to combine multiple formats
ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
// Maximum number of barcodes to find (0 = unlimited)
MaxParallelThreads = 4,
// Crop region for faster processing of specific areas
CropArea = null // Or specify a Rectangle
};
// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
// Process detected barcodes
foreach (var barcode in results)
{
Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
Imports IronBarCode
' Configure advanced reading options for difficult barcodes
Private options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.ExtremeDetail,
.ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
.MaxParallelThreads = 4,
.CropArea = Nothing
}
' Apply options when reading
Private results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)
' Process detected barcodes
For Each barcode In results
Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}")
Next barcode
*IronBarcode が高度なオプションを使用して正常に読み取った回転した QR コード*ExpectBarcodeTypes プロパティは、検索を特定の形式に制限することでパフォーマンスを大幅に向上させます。 問題のある画像で最大の精度を得るためには、画像フィルターを自動回転と組み合わせて使用します:
using IronBarCode;
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Apply image processing filters to enhance readability
ImageFilters = new ImageFilterCollection
{
new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
new ContrastFilter(2.0f), // Increases contrast
new SharpenFilter() // Reduces blur
},
// Automatically rotate to find barcodes at any angle
AutoRotate = true,
// Use multiple CPU cores for faster processing
Multithreaded = true
};
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
foreach (var result in results)
{
Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
Console.WriteLine($"Confidence: {result.Confidence}%");
Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
using IronBarCode;
BarcodeReaderOptions options = new BarcodeReaderOptions
{
// Apply image processing filters to enhance readability
ImageFilters = new ImageFilterCollection
{
new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
new ContrastFilter(2.0f), // Increases contrast
new SharpenFilter() // Reduces blur
},
// Automatically rotate to find barcodes at any angle
AutoRotate = true,
// Use multiple CPU cores for faster processing
Multithreaded = true
};
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
foreach (var result in results)
{
Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
Console.WriteLine($"Confidence: {result.Confidence}%");
Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
Imports IronBarCode
Private options As New BarcodeReaderOptions With {
.ImageFilters = New ImageFilterCollection From {
New AdaptiveThresholdFilter(9, 0.01F),
New ContrastFilter(2.0F),
New SharpenFilter()
},
.AutoRotate = True,
.Multithreaded = True
}
Private results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)
For Each result In results
Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}")
Console.WriteLine($"Confidence: {result.Confidence}%")
Console.WriteLine($"Position: X={result.X}, Y={result.Y}")
Next result
これらの高度な機能により、IronBarcodeは写真からのバーコードスキャン、セキュリティカメラ、または画像品質が大きく異なるモバイルデバイスのキャプチャに最適です。
PDFドキュメントから複数のバーコードをスキャンする方法は?
PDFバーコードスキャンは、請求書、出荷ラベル、在庫ドキュメントの処理に不可欠です。 IronBarcodeは、すべてのページのバーコードを効率的に読み取ります。
PDFファイルからのバーコード読み取り
using System;
using IronBarCode;
try
{
// Scan all pages of a PDF for barcodes
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
if (results != null && results.Count > 0)
{
foreach (var barcode in results)
{
// Access barcode data and metadata
string value = barcode.Text;
int pageNumber = barcode.PageNumber;
BarcodeEncoding format = barcode.BarcodeType;
byte[] binaryData = barcode.BinaryValue;
// Extract barcode image if needed
System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;
Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
}
}
else
{
Console.WriteLine("No barcodes found in the PDF.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading PDF: {ex.Message}");
}
using System;
using IronBarCode;
try
{
// Scan all pages of a PDF for barcodes
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
if (results != null && results.Count > 0)
{
foreach (var barcode in results)
{
// Access barcode data and metadata
string value = barcode.Text;
int pageNumber = barcode.PageNumber;
BarcodeEncoding format = barcode.BarcodeType;
byte[] binaryData = barcode.BinaryValue;
// Extract barcode image if needed
System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;
Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
}
}
else
{
Console.WriteLine("No barcodes found in the PDF.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading PDF: {ex.Message}");
}
Imports System
Imports IronBarCode
Try
' Scan all pages of a PDF for barcodes
Dim results As BarcodeResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf")
If results IsNot Nothing AndAlso results.Count > 0 Then
For Each barcode In results
' Access barcode data and metadata
Dim value As String = barcode.Text
Dim pageNumber As Integer = barcode.PageNumber
Dim format As BarcodeEncoding = barcode.BarcodeType
Dim binaryData() As Byte = barcode.BinaryValue
' Extract barcode image if needed
Dim barcodeImage As System.Drawing.Bitmap = barcode.BarcodeImage
Console.WriteLine($"Found {format} on page {pageNumber}: {value}")
Next barcode
Else
Console.WriteLine("No barcodes found in the PDF.")
End If
Catch ex As Exception
Console.WriteLine($"Error reading PDF: {ex.Message}")
End Try
異なるPDFページで見つかった複数バーコードを示すコンソール出力
特定のページ範囲または高度な PDF 処理の場合は、BarcodeReaderOptions を使用します。
// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
// Scan pages 1-5 only
PageNumbers = new[] { 1, 2, 3, 4, 5 },
// PDF-specific settings
PdfDpi = 300, // Higher DPI for better accuracy
ReadBehindVectorGraphics = true
};
BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
// Scan pages 1-5 only
PageNumbers = new[] { 1, 2, 3, 4, 5 },
// PDF-specific settings
PdfDpi = 300, // Higher DPI for better accuracy
ReadBehindVectorGraphics = true
};
BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
' Read only specific pages to improve performance
Dim pdfOptions As New BarcodeReaderOptions With {
.PageNumbers = { 1, 2, 3, 4, 5 },
.PdfDpi = 300,
.ReadBehindVectorGraphics = True
}
Dim results As BarcodeResults = BarcodeReader.ReadPdf("document.pdf", pdfOptions)
マルチフレームTIFF画像を処理する方法は?
ドキュメント スキャニングやファクシミリ システムで一般的なマルチフレームTIFFファイルは、PDFと同様の包括的なサポートを受けます。
異なるフレームにバーコードを持つマルチフレームTIFFファイル
using IronBarCode;
// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");
foreach (var result in multiFrameResults)
{
// Access frame-specific information
int frameNumber = result.PageNumber; // Frame number in TIFF
string barcodeValue = result.Text;
Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");
// Save individual barcode images if needed
result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
using IronBarCode;
// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");
foreach (var result in multiFrameResults)
{
// Access frame-specific information
int frameNumber = result.PageNumber; // Frame number in TIFF
string barcodeValue = result.Text;
Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");
// Save individual barcode images if needed
result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
Imports IronBarCode
' TIFF files are processed similarly to regular images
' Each frame is scanned automatically
Private multiFrameResults As BarcodeResults = BarcodeReader.Read("Multiframe.tiff")
For Each result In multiFrameResults
' Access frame-specific information
Dim frameNumber As Integer = result.PageNumber ' Frame number in TIFF
Dim barcodeValue As String = result.Text
Console.WriteLine($"Frame {frameNumber}: {barcodeValue}")
' Save individual barcode images if needed
If result.BarcodeImage IsNot Nothing Then
result.BarcodeImage.Save($"barcode_frame_{frameNumber}.png")
End If
Next result
同じ BarcodeReaderOptions が、画像フィルタや回転設定を含む TIFF 処理にも適用されます。 詳細なTIFF処理シナリオについては、画像処理チュートリアルを参照してください。
マルチスレッド処理で処理速度を上げることができますか?
複数のドキュメントを処理することで並列処理から大きな利点を得られます。 IronBarcodeは最適なパフォーマンスのために利用可能なCPUコアを自動的に利用します。
using IronBarCode;
// List of documents to process - mix of formats supported
var documentBatch = new[]
{
"invoice1.pdf",
"shipping_label.png",
"inventory_sheet.tiff",
"product_catalog.pdf"
};
// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
// Enable parallel processing across documents
Multithreaded = true,
// Limit threads if needed (0 = use all cores)
MaxParallelThreads = Environment.ProcessorCount,
// Apply consistent settings to all documents
Speed = ReadingSpeed.Balanced,
ExpectBarcodeTypes = BarcodeEncoding.All
};
// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);
// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);
foreach (var docGroup in resultsByDocument)
{
Console.WriteLine($"\nDocument: {docGroup.Key}");
foreach (var barcode in docGroup)
{
Console.WriteLine($" - {barcode.BarcodeType}: {barcode.Text}");
}
}
using IronBarCode;
// List of documents to process - mix of formats supported
var documentBatch = new[]
{
"invoice1.pdf",
"shipping_label.png",
"inventory_sheet.tiff",
"product_catalog.pdf"
};
// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
// Enable parallel processing across documents
Multithreaded = true,
// Limit threads if needed (0 = use all cores)
MaxParallelThreads = Environment.ProcessorCount,
// Apply consistent settings to all documents
Speed = ReadingSpeed.Balanced,
ExpectBarcodeTypes = BarcodeEncoding.All
};
// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);
// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);
foreach (var docGroup in resultsByDocument)
{
Console.WriteLine($"\nDocument: {docGroup.Key}");
foreach (var barcode in docGroup)
{
Console.WriteLine($" - {barcode.BarcodeType}: {barcode.Text}");
}
}
Imports Microsoft.VisualBasic
Imports IronBarCode
' List of documents to process - mix of formats supported
Private documentBatch = { "invoice1.pdf", "shipping_label.png", "inventory_sheet.tiff", "product_catalog.pdf" }
' Configure for batch processing
Private batchOptions As New BarcodeReaderOptions With {
.Multithreaded = True,
.MaxParallelThreads = Environment.ProcessorCount,
.Speed = ReadingSpeed.Balanced,
.ExpectBarcodeTypes = BarcodeEncoding.All
}
' Process all documents in parallel
Private batchResults As BarcodeResults = BarcodeReader.Read(documentBatch, batchOptions)
' Group results by source document
Private resultsByDocument = batchResults.GroupBy(Function(r) r.Filename)
For Each docGroup In resultsByDocument
Console.WriteLine($vbLf & "Document: {docGroup.Key}")
For Each barcode In docGroup
Console.WriteLine($" - {barcode.BarcodeType}: {barcode.Text}")
Next barcode
Next docGroup
この並列アプローチはドキュメントを同時に処理し、マルチコアシステムでスキャン時間を最大75%短縮します。 企業規模のバーコード処理には、パフォーマンス最適化ガイドを探求してください。
まとめ
IronBarcodeは複雑なバーコードスキャンを単純なC#コードに変換します。 在庫システム、ドキュメントプロセッサ、またはモバイルアプリケーションを構築しようとしているか否かにかかわらず、ライブラリは完璧なデジタルバーコードから困難な実世界のキャプチャまでを処理します。
カバーされている主な機能:
- 画像からの単一行バーコード読み取り
- 破損または回転した BarCode 用の高度なオプション
- 包括的なPDFおよびTIFFドキュメントのスキャン
- マルチスレッドによる高性能バッチ処理
- すべての主要なバーコードフォーマットのサポート
さらなる読み物
これらのリソースでバーコード処理機能を拡張:
- バーコード生成チュートリアル - カスタムバーコードを作成する。
- QRコードガイド](/csharp/barcode/tutorials/csharp-qr-code-generator/) - 特殊なQRコード。
BarcodeReaderクラスリファレンス- 完全なAPIドキュメント- トラブルシューティングガイド - 一般的な問題と解決策
ソースコードダウンロード
これらの例を自分で実行:
あなたのアプリケーションでバーコードスキャンを実装する準備は整いましたか? 無料トライアルを開始して、.NETプロジェクトにプロフェッショナルなバーコード読み取りを追加してください。
よくある質問
.NETプロジェクトにバーコード読み取りライブラリをインストールするにはどうすればよいですか?
dotnet add package BarCodeというコマンドを使用してNuGetパッケージマネージャーを通じてIronBarcodeライブラリをインストールすることができます。または、Visual StudioのNuGetインターフェースを使用することもできます。手動インストールのためにDLLをダウンロードするという方法もあります。
C#を使用して画像からバーコードを読み取る方法は何ですか?
IronBarcodeからBarcodeReader.Readメソッドを1行のコードで使用します: var results = BarcodeReader.Read('image.png'); このメソッドは画像内のすべてのバーコード形式を検出して読み取ります。
単一の画像またはドキュメントで複数のバーコードを検出することは可能ですか?
はい、IronBarcodeは画像、PDF、またはマルチフレームTIFF内の複数のバーコードを自動的に検出して読み取り、各バーコードの値、タイプ、および位置をBarcodeResultsコレクションで返します。
C#を使用してPDFからバーコードを読む方法は何ですか?
IronBarcodeのBarcodeReader.ReadPdfメソッドを使用して、PDFドキュメントのすべてのページをスキャンします: var results = BarcodeReader.ReadPdf('document.pdf'); 各結果にはバーコードが発見されたページ番号が含まれます。
バーコード画像がぼやけていたり回転している場合はどうすればよいですか?
画像フィルタ SharpenFilter または AdaptiveThresholdFilter を適用し、AutoRotate = true を設定して難しい画像を処理するためにBarcodeReaderOptionsを設定します。より良い精度のためにSpeed = ExtremeDetailを使用します。
.NETアプリケーションでサポートされているバーコード形式はどれですか?
IronBarcodeは、QRコード、Code 128、Code 39、EAN-13、UPC-A、Data Matrix、PDF417、その他の主要なバーコード形式をすべてサポートしています。BarcodeEncoding.Allを使用して任意のサポートされた形式をスキャンします。
C#アプリケーションでバーコードスキャンのパフォーマンスをどのように向上させることができますか?
ExpectBarcodeTypesを使用して予想されるバーコードタイプを指定し、マルチスレッド処理を有効にし、適切なSpeed設定を選択してパフォーマンスを向上させます。バッチタスクの場合、ファイルパス付きのBarcodeReader.Readを使用します。
バーコード読み取りエラーを処理するための推奨アプローチは何ですか?
try-catchブロックでバーコード読み取りをカプセル化し、結果がnullまたは空であるかを確認します。IronBarcodeは、検出の信頼性を示す詳細なエラーメッセージとConfidenceプロパティを提供します。
スキャン後にバーコード画像を抽出できますか?
はい、IronBarcodeのBarcodeResultには、検出されたバーコードのBitmapを含むBarcodeImageプロパティが含まれており、それを保存したり別に処理したりできます。
PDFドキュメント内の特定のページからバーコードを読む方法は何ですか?
BarcodeReaderOptionsのPageNumbersプロパティを設定してページを指定します: options.PageNumbers = new[] {1, 2, 3}; これにより指定されたページでのみスキャンすることでパフォーマンスが最適化されます。
.NETでのバーコードスキャンに対応した画像形式は何ですか?
IronBarcodeは、PNG、JPEG、BMP、GIF、TIFF(マルチフレームを含む)、PDFの形式でのスキャンをサポートしています。ファイルパス、ストリーム、またはバイト配列から画像をロードできます。
C#でスキャンされたバーコードからバイナリデータにアクセスする方法は何ですか?
特に圧縮情報やバイナリプロトコルなど、非テキストデータを含むバーコードの生のバイナリデータを取得するには、BarcodeResultのBinaryValueプロパティを使用します。

