IronBarcode 教程 在 .NET 中读取条形码 C# Barcode Scanner: Read Barcodes & QR Codes in .NET Applications Jacob Mellor 已更新:七月 22, 2025 Download IronBarcode NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article This article was translated from English: Does it need improvement? Translated View the article in English Need to quickly scan barcodes or QR codes in your .NET application? IronBarcode makes barcode reading simple and reliable, whether you're processing perfect digital images or challenging real-world photos. This guide shows you exactly how to implement barcode scanning in C# with practical examples you can use immediately. Quickstart: Read a Barcode from a File Instantly This quick example shows you how easy it is to get started with IronBarcode. In just one line of code, you can read barcodes from an image file—no complex setup required. Get started making PDFs with NuGet now: Install IronBarcode with NuGet Package Manager PM > Install-Package BarCode Copy and run this code snippet. var results = IronBarCode.BarcodeReader.Read("path/to/barcode.png"); Deploy to test on your live environment Start using IronBarcode in your project today with a free trial Free 30 day Trial Minimal Workflow (5 steps) Install IronBarcode from NuGet or via DLL download Use the BarcodeReader.Read method to scan any barcode or QR code Read multiple barcodes or QR codes in a single scan, PDF, or multiframe TIFF file Enable IronBarcode to decode imperfect scans and photos with advanced filters Download the tutorial project and start scanning immediately How do I install IronBarcode in my .NET project? IronBarcode installs easily through NuGet Package Manager or by downloading the DLL directly. The NuGet installation is the recommended approach as it automatically manages dependencies and updates. 今天在您的项目中使用 IronBarcode,免费试用。 第一步: 免费开始 Install-Package BarCode After installation, add using IronBarCode; to your C# files to access the barcode scanning functionality. For detailed installation instructions across different development environments, check our installation guide. How can I read my first barcode using C#? Reading barcodes with IronBarcode requires just one line of code. The library automatically detects barcode formats and extracts all encoded data. A standard Code128 barcode that IronBarcode can read instantly 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."); } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel The BarcodeReader.Read method returns a BarcodeResults collection containing all detected barcodes. Each BarcodeResult provides access to the barcode's text value, format type, position coordinates, and binary data. This approach works seamlessly with common barcode formats including Code128, Code39, QR codes, and Data Matrix codes. What options help read challenging or damaged barcodes? Real-world barcode scanning often involves imperfect images - skewed angles, poor lighting, or partial damage. IronBarcode's advanced options handle these challenges effectively. 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 $vbLabelText $csharpLabel A rotated QR code that IronBarcode successfully reads using advanced options The ExpectBarcodeTypes property significantly improves performance by limiting the search to specific formats. For maximum accuracy with problematic images, combine image filters with automatic rotation: 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 $vbLabelText $csharpLabel These advanced features make IronBarcode ideal for scanning barcodes from photos, security cameras, or mobile device captures where image quality varies significantly. How do I scan multiple barcodes from PDF documents? PDF barcode scanning is essential for processing invoices, shipping labels, and inventory documents. IronBarcode reads all barcodes across every page efficiently. Reading barcodes from PDF files 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 $vbLabelText $csharpLabel Console output showing multiple barcodes found across different PDF pages For specific page ranges or advanced PDF processing, use 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) $vbLabelText $csharpLabel Learn more about PDF barcode extraction techniques in our detailed examples. How can I process multiframe TIFF images? Multiframe TIFF files, common in document scanning and fax systems, receive the same comprehensive support as PDFs. A multiframe TIFF file with barcodes on different frames 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 $vbLabelText $csharpLabel The same BarcodeReaderOptions apply to TIFF processing, including image filters and rotation settings. For detailed TIFF handling scenarios, see our image processing tutorials. Can I speed up processing with multithreading? Processing multiple documents benefits dramatically from parallel processing. IronBarcode automatically utilizes available CPU cores for optimal performance. 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 $vbLabelText $csharpLabel This parallel approach processes documents simultaneously, reducing total scanning time by up to 75% on multicore systems. For enterprise-scale barcode processing, explore our performance optimization guide. Summary IronBarcode transforms complex barcode scanning into straightforward C# code. Whether you're building inventory systems, document processors, or mobile applications, the library handles everything from pristine digital barcodes to challenging real-world captures. Key capabilities covered: Single-line barcode reading from images Advanced options for damaged or rotated barcodes Comprehensive PDF and TIFF document scanning High-performance batch processing with multithreading Support for all major barcode formats Further Reading Expand your barcode processing capabilities with these resources: Barcode Generation Tutorial - Create custom barcodes QR Code Guide - Specialized QR code features BarcodeReader Class Reference - Complete API documentation Troubleshooting Guide - Common issues and solutions Source Code Downloads Run these examples yourself: Tutorial GitHub Repository C# Source Code in a Zip File Ready to implement barcode scanning in your application? Start your free trial and add professional barcode reading to your .NET project today. 立即开始使用 IronBarcode。 免费开始 常见问题解答 .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 属性获取原始二进制数据,对于包含非文本数据如压缩信息或二进制协议的条形码特别有用。 Jacob Mellor 立即与工程团队聊天 首席技术官 Jacob Mellor 是 Iron Software 的首席技术官,是 C# PDF 技术的先锋工程师。作为 Iron Software 核心代码库的原始开发者,自公司成立以来,他就塑造了公司的产品架构,并与首席执行官 Cameron Rimington 一起将其转变成一家公司,拥有50多人,服务于 NASA、特斯拉和全球政府机构。Jacob 拥有曼彻斯特大学 (1998-2001) 的一级荣誉土木工程学士学位。1999 年在伦敦创办了自己的第一家软件公司,并于 2005 年创建了他的第一个 .NET 组件后,他专注于解决微软生态系统中的复杂问题。他的旗舰 IronPDF 和 IronSuite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。 准备开始了吗? Nuget 下载 1,935,276 | 版本: 2025.11 刚刚发布 免费 NuGet 下载 总下载量:1,935,276 查看许可证