如何使用 C# 读取条形码

C# Barcode Scanner: Read Barcodes & QR Codes in .NET Applications

This article was translated from English: Does it need improvement?
Translated
View the article in English

需要在 .NET 应用程序中快速扫描条形码或二维码吗? 无论您是处理完美的数字图像还是具有挑战性的真实世界照片,IronBarcode 都能让条形码读取变得简单可靠。 本指南将通过您可以立即使用的实际示例,向您展示如何在 C# 中实现条形码扫描。

快速入门:立即从文件读取条形码

这个简单的示例向您展示了IronBarcode入门是多么容易。 只需一行代码,即可从图像文件中读取条形码——无需复杂的设置。

  1. 使用 NuGet 包管理器安装 https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 复制并运行这段代码。

    var results = IronBarCode.BarcodeReader.Read("path/to/barcode.png");
  3. 部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronBarcode

    arrow pointer

如何在我的.NET项目中安装IronBarcode?

IronBarcode 可以通过 NuGet 包管理器轻松安装,也可以直接下载 DLL 文件进行安装。 建议使用 NuGet 安装,因为它能够自动管理依赖项和更新。

Install-Package BarCode

安装后,将using IronBarCode;添加到您的C#文件中以访问条码扫描功能。 有关不同开发环境下的详细安装说明,请查看我们的安装指南

如何使用 C# 读取我的第一个条形码?

using IronBarcode 读取条形码只需要一行代码。 该库可自动检测条形码格式并提取所有编码数据。

Code128条码可供扫描 - 包含文本'https://ironsoftware.com/csharp/barcode/' *IronBarcode 可以立即读取的标准 Code128 条形码*
:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-3.cs
using IronBarCode;

BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    // Choose which filters are to be applied (in order)
    ImageFilters = new ImageFilterCollection() {
        new AdaptiveThresholdFilter(),
    },

    // Uses machine learning to auto rotate the barcode
    AutoRotate = true,
};

// Read barcode
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);
Imports IronBarCode

Private options As New BarcodeReaderOptions() With {
	.ImageFilters = New ImageFilterCollection() From {New AdaptiveThresholdFilter()},
	.AutoRotate = True
}

' Read barcode
Private results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)
$vbLabelText   $csharpLabel

BarcodeResults集合。 每个BarcodeResult提供对条码文本值、格式类型、位置坐标和二进制数据的访问。 这种方法可以与常见的条形码格式无缝配合,包括 Code128、Code39、QR 码和 Data Matrix 码。

哪些方法可以帮助读取难以辨认或损坏的条形码?

现实世界中的条形码扫描经常会遇到图像不完美的情况——角度倾斜、光线不足或部分损坏。 IronBarcode 的高级选项可以有效应对这些挑战。

:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-4.cs
using IronBarCode;
using System;

// Multiple barcodes may be scanned up from a single document or image. A PDF document may also used as the input image
BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

// Work with the results
foreach (var pageResult in results)
{
    string Value = pageResult.Value;
    int PageNum = pageResult.PageNumber;
    System.Drawing.Bitmap Img = pageResult.BarcodeImage;
    BarcodeEncoding BarcodeType = pageResult.BarcodeType;
    byte[] Binary = pageResult.BinaryValue;
    Console.WriteLine(pageResult.Value + " on page " + PageNum);
}
Imports IronBarCode
Imports System

' Multiple barcodes may be scanned up from a single document or image. A PDF document may also used as the input image
Private results As BarcodeResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf")

' Work with the results
For Each pageResult In results
	Dim Value As String = pageResult.Value
	Dim PageNum As Integer = pageResult.PageNumber
	Dim Img As System.Drawing.Bitmap = pageResult.BarcodeImage
	Dim BarcodeType As BarcodeEncoding = pageResult.BarcodeType
	Dim Binary() As Byte = pageResult.BinaryValue
	Console.WriteLine(pageResult.Value & " on page " & PageNum)
Next pageResult
$vbLabelText   $csharpLabel
QR码旋转45度展示了IronBarcode的旋转处理 *IronBarcode 使用高级选项成功读取了旋转后的二维码*

ExpectBarcodeTypes属性通过将搜索限定为特定格式显著提高性能。 为了最大限度地提高处理问题图像的精度,请将图像滤波器与自动旋转功能结合使用:

:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-5.cs
using IronBarCode;

// Multi frame TIFF and GIF images can also be scanned
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");

foreach (var pageResult in multiFrameResults)
{
    //...
}
Imports IronBarCode

' Multi frame TIFF and GIF images can also be scanned
Private multiFrameResults As BarcodeResults = BarcodeReader.Read("Multiframe.tiff")

For Each pageResult In multiFrameResults
	'...
Next pageResult
$vbLabelText   $csharpLabel

IronBarcode 的这些高级功能使其成为扫描照片、监控摄像头或移动设备拍摄的图像中条形码的理想选择,尤其适用于图像质量差异很大的情况。

如何扫描PDF文档中的多个条形码?

PDF条形码扫描对于处理发票、发货标签和库存文件至关重要。 IronBarcode 可以高效读取每一页上的所有条形码。

从PDF文件中读取条形码

:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-6.cs
using IronBarCode;

// The Multithreaded property allows for faster barcode scanning across multiple images or PDFs. All threads are automatically managed by IronBarCode.
var ListOfDocuments = new[] { "image1.png", "image2.JPG", "image3.pdf" };

BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    // Enable multithreading
    Multithreaded = true,
};

BarcodeResults batchResults = BarcodeReader.Read(ListOfDocuments, options);
Imports IronBarCode

' The Multithreaded property allows for faster barcode scanning across multiple images or PDFs. All threads are automatically managed by IronBarCode.
Private ListOfDocuments = { "image1.png", "image2.JPG", "image3.pdf" }

Private options As New BarcodeReaderOptions() With {.Multithreaded = True}

Private batchResults As BarcodeResults = BarcodeReader.Read(ListOfDocuments, options)
$vbLabelText   $csharpLabel

多个条码检测于PDF页面展示了控制台输出 控制台输出显示在不同的 PDF 页面中发现了多个条形码

对于特定页面范围或高级PDF处理,使用BarcodeReaderOptions

:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-7.cs
// Read only specific pages to improve performance
PdfBarcodeReaderOptions pdfOptions = new PdfBarcodeReaderOptions
{
    // Scan pages 1-5 only
    PageNumbers = new[] { 1, 2, 3, 4, 5 },

    // PDF-specific settings
    DPI = 300 // Higher DPI for better accuracy
};

BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
Imports System

' Read only specific pages to improve performance
Dim pdfOptions As New PdfBarcodeReaderOptions With {
    ' Scan pages 1-5 only
    .PageNumbers = New Integer() {1, 2, 3, 4, 5},

    ' PDF-specific settings
    .DPI = 300 ' Higher DPI for better accuracy
}

Dim results As BarcodeResults = BarcodeReader.ReadPdf("document.pdf", pdfOptions)
$vbLabelText   $csharpLabel

如何处理多帧TIFF图像?

多帧 TIFF 文件(常见于文档扫描和传真系统)与 PDF 文件一样,都得到了全面的支持。

多帧TIFF包含跨帧的多个条码 一个多帧 TIFF 文件,不同帧上带有条形码。

:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-8.cs
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
Dim 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
    result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png")
Next
$vbLabelText   $csharpLabel

相同的BarcodeReaderOptions适用于TIFF处理,包括图像滤镜和旋转设置。 有关 TIFF 处理场景的详细说明,请参阅我们的图像处理教程

我能否利用多线程来加快处理速度?

并行处理能极大地提高多文档处理效率。 IronBarcode 会自动利用可用的 CPU 核心,以实现最佳性能。

:path=/static-assets/barcode/content-code-examples/tutorials/reading-barcodes-9.cs
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 each document, tracking the source path externally
foreach (var document in documentBatch)
{
    BarcodeResults results = BarcodeReader.Read(document, batchOptions);

    Console.WriteLine($"\nDocument: {document}");
    foreach (var barcode in results)
    {
        Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}");
    }
}
Imports IronBarCode

' List of documents to process - mix of formats supported
Dim documentBatch = New String() {
    "invoice1.pdf",
    "shipping_label.png",
    "inventory_sheet.tiff",
    "product_catalog.pdf"
}

' Configure for batch processing
Dim batchOptions As New BarcodeReaderOptions With {
    ' 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 each document, tracking the source path externally
For Each document In documentBatch
    Dim results As BarcodeResults = BarcodeReader.Read(document, batchOptions)

    Console.WriteLine(vbCrLf & "Document: " & document)
    For Each barcode In results
        Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}")
    Next
Next
$vbLabelText   $csharpLabel

这种并行方法可以同时处理文档,在多核系统上可将总扫描时间缩短高达 75%。 对于企业级条码处理,请查阅我们的性能优化指南

摘要

IronBarcode 将复杂的条形码扫描转换为简单的 C# 代码。 无论您是构建库存系统、文档处理器还是移动应用程序,该库都能处理从完美的数字条形码到具有挑战性的现实世界采集的一切。

主要功能涵盖:

  • 从图像中读取单行条形码
  • 针对损坏或旋转条形码的高级选项
  • 全面扫描 PDF 和 TIFF 文档
  • 高性能多线程批处理 支持所有主流条形码格式

进一步阅读

利用以下资源扩展您的条形码处理能力:

条形码生成教程- 创建自定义条形码

源代码下载

请自行运行以下示例:

-教程 GitHub 仓库

准备好在您的应用程序中实现条形码扫描了吗? 立即开始免费试用,并将专业的条形码读取功能添加到您的.NET项目中。

立即开始使用 IronBarcode。
green arrow pointer

常见问题解答

.NET 项目中如何安装条形码读取库?

您可以通过 NuGet 包管理器使用命令 dotnet add package BarCode 或通过 Visual Studio 的 NuGet 接口安装 IronBarcode 库。或者,下载 DLL 手动安装。

using C# 从图像读取条形码的方法是什么?

using IronBarcode 的 BarcodeReader.Read 方法只需一行代码:var results = BarcodeReader.Read('image.png'); 该方法检测并读取图像中存在的所有条形码格式。

是否可以在单个图像或文档中检测多个条形码?

是的,IronBarcode 可以自动检测并读取图像、PDF 或多帧 TIFF 中的多个条形码,返回每个条形码的值、类型和在 BarcodeResults 集合中的位置。

如何使用 C# 从 PDF 读取条形码?

using IronBarcode 的 BarcodeReader.ReadPdf 方法扫描 PDF 文档的所有页面:var results = BarcodeReader.ReadPdf('document.pdf'); 每个结果包括找到条形码的页码。

如果条形码图像模糊或旋转,我该怎么办?

通过设置 AutoRotate = true 配置 BarcodeReaderOptions 来处理具有挑战性的图像,并应用 SharpenFilterAdaptiveThresholdFilter 等图像过滤器。使用 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# 中访问扫描条形码的二进制数据?

利用 BarcodeResultBinaryValue 属性获取原始二进制数据,对于包含非文本数据如压缩信息或二进制协议的条形码特别有用。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

准备开始了吗?
Nuget 下载 2,317,217 | 版本: 2026.7 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package BarCode
运行示例 观看您的字符串变成 BarCode。