C# Barcode Scanner: Read Barcodes & QR Codes in .NET Applications
需要在您的 .NET 应用程序中快速扫描 BARCODE 或 QR 码吗? 无论您处理的是完美的数字图像还是复杂的现实世界照片,IronBarcode 都能让条形码读取变得简单可靠。 本指南将通过可立即使用的实用示例,向您详细展示如何在 C# 中实现 BarCode 扫描。
快速入门:即时读取文件中的BarCode
这个简短示例向您展示了 IronBarcode 的入门是多么简单。 只需一行代码,即可从图像文件中读取BARCODE——无需复杂配置。
简易工作流程(5个步骤)
- 通过 NuGet 或 DLL 下载安装 IronBarcode
- 使用
BarcodeReader.Read方法扫描任何BARCODE或QR码 - 在单次扫描、PDF 或多帧 TIFF 文件中读取多个 BARCODE 或 QR 码
- 启用 IronBarcode 的高级滤镜功能,可解码质量不佳的扫描件和照片
- 下载教程项目,立即开始扫描
如何在我的 .NET 项目中安装 IronBarcode?
IronBarcode 可通过 NuGet 包管理器轻松安装,或直接下载 DLL 文件进行安装。 建议采用 NuGet 安装方式,因为它能自动管理依赖项和更新。
Install-Package BarCode
安装完成后,在 C# 文件中添加 using IronBarCode; 以调用 BarCode 扫描功能。 有关不同开发环境的详细安装说明,请查阅我们的安装指南。
如何使用 C# 读取我的第一个 BARCODE?
using IronBarcode 读取 BARCODE 只需一行代码。 该库可自动检测BarCode格式并提取所有编码数据。
*IronBarcode 可即时读取的标准 Code128 BarCode*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.Co/unt > 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.Co/nfidence - 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.Co/unt > 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.Co/nfidence - 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 集合,其中包含所有检测到的 BarCode。 每个 BarcodeResult 均可访问 BarCode 的文本值、格式类型、位置坐标和二进制数据。 该方案可无缝兼容常见的BarCode格式,包括 Code128、Code39、QR码和数据矩阵码。
有哪些选项有助于读取难以识别或受损的BarCode?
实际的BARCODE扫描往往涉及图像质量不佳的情况——例如角度歪斜、光线不足或部分损坏。 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.Co/de128,
// 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.Co/de128,
// 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
Dim options As New BarcodeReaderOptions With {
' 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 Or BarcodeEncoding.Code128,
' Maximum number of barcodes to find (0 = unlimited)
.MaxParallelThreads = 4,
' Crop region for faster processing of specific areas
.CropArea = Nothing ' Or specify a Rectangle
}
' Apply options when reading
Dim 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.Co/nfidence}%");
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.Co/nfidence}%");
Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
Imports IronBarCode
Dim options As New BarcodeReaderOptions With {
.ImageFilters = New ImageFilterCollection From {
New AdaptiveThresholdFilter(9, 0.01F), ' Handles varying lighting
New ContrastFilter(2.0F), ' Increases contrast
New SharpenFilter() ' Reduces blur
},
.AutoRotate = True, ' Automatically rotate to find barcodes at any angle
.Multithreaded = True ' Use multiple CPU cores for faster processing
}
Dim 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
这些高级功能使 IronBarcode 成为扫描照片、监控摄像头或移动设备截图中 BarCode 的理想工具,即使图像质量存在显著差异也能胜任。
如何从 PDF 文档中扫描多个 BarCode?
PDF 条形码扫描对于处理发票、运输标签和库存文件至关重要。 IronBarcode 能高效读取所有页面上的所有 BarCode。
从 PDF 文件中读取 BarCode
using System;
using IronBarCode;
try
{
// Scan all pages of a PDF for barcodes
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
if (results != null && results.Co/unt > 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.Co/unt > 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
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 页面上发现了多个 BarCode
如需处理特定页码范围或进行高级 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 文件一样,同样受到全面支持。
包含不同帧上 BarCode 的多帧 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
关于 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%。 如需进行Enterprise级BarCode处理,请参阅我们的性能优化指南。
摘要
IronBarcode 将复杂的 BarCode 扫描功能转化为简洁的 C# 代码。 无论您是在构建库存系统、文档处理程序还是移动应用程序,该库都能处理从清晰的数字BARCODE到复杂的现实场景捕获等各种需求。
涵盖的主要功能:
- 从图像中读取单行BarCode
- 针对损坏或旋转BarCode的高级选项
- 全面的 PDF 和 TIFF 文档扫描
- 支持多线程的高性能批处理
- 支持所有主流BARCODE格式
延伸阅读
借助以下资源,拓展您的BarCode处理能力:
- BarCode生成教程 - 创建自定义BarCode
- QR Code指南 - 专业的QR Code功能
BarcodeReader类参考 - 完整的 API 文档- 故障排除指南 - 常见问题与解决方案
源代码下载
请亲自运行以下示例:
准备好在您的应用程序中实现BarCode扫描功能了吗? 立即开始免费试用,为您的 .NET 项目添加 Professional 版 BarCode 读取功能。
常见问题解答
.NET 项目中如何安装条形码读取库?
您可以通过 NuGet 包管理器使用命令 dotnet add package BarCode 或通过 Visual Studio 的 NuGet 接口安装 IronBarcode 库。或者,下载 DLL 手动安装。
使用 C# 从图像读取条形码的方法是什么?
使用 IronBarcode 的 BarcodeReader.Read 方法只需一行代码:var results = BarcodeReader.Read('image.png'); 该方法检测并读取图像中存在的所有条形码格式。
是否可以在单个图像或文档中检测多个条形码?
是的,IronBarcode 可以自动检测并读取图像、PDF 或多帧 TIFF 中的多个条形码,返回每个条形码的值、类型和在 BarcodeResults 集合中的位置。
如何使用 C# 从 PDF 读取条形码?
使用 IronBarcode 的 BarcodeReader.ReadPdf 方法扫描 PDF 文档的所有页面:var results = BarcodeReader.ReadPdf('document.pdf'); 每个结果包括找到条形码的页码。
如果条形码图像模糊或旋转,我该怎么办?
通过设置 AutoRotate = true 配置 BarcodeReaderOptions 来处理具有挑战性的图像,并应用 SharpenFilter 或 AdaptiveThresholdFilter 等图像过滤器。使用 Speed = ExtremeDetail 以提高精度。
.NET 应用程序支持哪些条形码格式?
IronBarcode 支持所有主要的条形码格式,例如 QR 码、Code 128、Code 39、EAN-13、UPC-A、Data Matrix、PDF417 等。利用 BarcodeEncoding.All 扫描任何支持的格式。
如何提高 C# 应用程序中的条形码扫描性能?
通过指定预期的条形码类型、启用多线程处理和选择合适的 Speed 设置来提高性能。对于批处理任务,利用 BarcodeReader.Read 使用文件路径。
处理条形码读取错误的推荐方法是什么?
将条形码读取封装在 try-catch 块中,并验证结果是否为空或为空。IronBarcode 提供详细的错误信息和一个 Confidence 属性以指示检测可靠性。
在扫描后我可以提取条形码图像吗?
是的,IronBarcode 的 BarcodeResult 包括一个 BarcodeImage 属性,其中包含检测到的条形码的位图,可以单独保存或处理。
如何从 PDF 文档的特定页面读取条形码?
在 BarcodeReaderOptions 中设置 PageNumbers 属性指定页面:options.PageNumbers = new[] {1, 2, 3}; 这通过仅扫描指定页面来优化性能。
在 .NET 中兼容哪些图像格式用于条形码扫描?
IronBarcode 支持扫描 PNG、JPEG、BMP、GIF、TIFF(包括多帧)和 PDF 格式。您可以从文件路径、流或字节数组加载图像。
如何在 C# 中访问扫描条形码的二进制数据?
利用 BarcodeResult 的 BinaryValue 属性获取原始二进制数据,对于包含非文本数据如压缩信息或二进制协议的条形码特别有用。

