如何在 C# 中从图像读取条形码

如何使用 C# 从图像中读取条形码

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

IronBarcode 在 C# 中使用 BarcodeReader.Read() 只需一行代码即可从图像中读取条形码,支持多种图像格式,包括 PNG、JPEG、GIF、BMP、TIFF 和 SVG,并可自定义选项以提高性能和准确性。

IronBarcode 的一个关键特性是它能够开箱即用地读取多种图像格式的条形码。 IronBarcode目前支持以下图像格式:

  • 可缩放矢量图形 (SVG)
  • 联合图像专家组 (JPEG)
  • 便携式网络图形 (PNG)
  • 图形交换格式 (GIF)
  • 标签图像文件格式 (TIFF) 位图图像文件(BMP)

This is made possible with the help of our open source library, IronDrawing. 有关 支持的条形码格式(包括一维和二维类型)的完整列表,请查看我们的综合文档。

快速入门:几秒钟内从图像中读取条形码

只需简单调用 IronBarCode.BarcodeReader.Read() 即可直接从 PNG、JPEG、GIF、BMP 和 TIFF 等图像文件格式中提取条形码数据。 立即开始使用——无需复杂设置,即可立即见效。

Nuget Icon立即开始使用 NuGet 创建 PDF 文件:

  1. 使用 NuGet 包管理器安装 IronBarcode

    PM > Install-Package BarCode

  2. 复制并运行这段代码。

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

    立即开始在您的项目中使用 IronBarcode,免费试用!
    arrow pointer

如何直接从图像中读取 BarCode?

下面介绍如何使用 IronBarcode 读取条码。 有关 在 C# / .NET 中读取 BarCode 的全面教程,包括 PDF 处理和批处理操作的高级技术,请访问我们的详细指南:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-images-1.cs
using IronBarCode;
using System;

var myBarcode = BarcodeReader.Read(@"image_file_path.jpg"); //image file path

foreach (var item in myBarcode)
{
    Console.WriteLine(item.ToString());
}
Imports IronBarCode
Imports System

Private myBarcode = BarcodeReader.Read("image_file_path.jpg") 'image file path

For Each item In myBarcode
	Console.WriteLine(item.ToString())
Next item
$vbLabelText   $csharpLabel
Sample QR code with finder patterns for testing barcode reading from images
样品测试二维码
Sample barcode with black vertical lines on white background for testing image-based barcode reading
样品测试条形码

想知道样品中的条形码值是什么吗?试试这段代码片段吧!

要使用 IronBarcode,首先需要做的是通过 Microsoft Visual Studio NuGet 包管理器将 IronBarcode 库安装到您的项目中,如下图所示。 这将允许您访问 IronBarcode 的 BarcodeReader.Read() 方法来直接读取条码图像。

IronBarcode 提供了简单易用的功能,用户只需使用BarcodeReader.Read()即可读取项目中已包含的图像文件,只需将文件名字符串或文件路径字符串作为该方法的参数即可。 最佳实践是在方法中指定文件路径时使用字符串字面量"@",以避免在文件路径字符串中添加多个转义字符"\"。

BarcodeReader.Read()方法调用的末尾附加Values()方法,以将条形码值作为System.String[]对象获取。

要将结果输出到控制台,可以使用foreach循环遍历存储在string[]数组中的值,并在循环块内调用Console.WriteLine()方法,并将迭代器变量作为参数。

IronBarcode 能够读取一维条码格式(Codabar, Code128, Code39, Code93, EAN13, EAN18ITF, MSI, UPCA, UPCE) 以及二维条码格式 (Aztec, DataMatrix, QRCode) 的各种图像格式。

如何配置条码阅读器选项以提高性能?

条形码读取速度太慢? 图片中的条形码是否太小,导致 IronBarcode 无法读取? 只想读取图像的特定区域? 想从包含多种条形码的图像中只读取特定类型的条形码吗? 想要提高整体阅读性能吗?

BarcodeReaderOptions 允许用户调整或调整条码阅读器的行为,以解决所有这些问题。 有关 设置条码阅读器选项的详细示例,请查看我们的综合指南。以下章节将逐一讨论 BarcodeReaderOptions 中可用的所有可调整属性。

如何指定要读取图像的哪个区域?

CropAreaBarcodeReaderOptionsIron Software.Drawing.CropRectangle类型的一个属性,允许用户指定 IronBarcode 应该读取的图像区域。 这有助于提高读取性能,因为条形码读取器无需扫描整个图像来查找条形码,同时由于读取区域已指定,读取精度也得以提高。 了解有关如何指定作物区域以获得最佳性能的更多信息。

要设置CropArea属性,只需实例化一个新的Rectangle类型对象,并将矩形的坐标、宽度和长度指定为参数即可。 接受的测量单位为像素 (px)。

// Example of setting CropArea
var cropArea = new IronSoftware.Drawing.Rectangle(x: 100, y: 100, width: 300, height: 300);
var options = new BarcodeReaderOptions()
{
    CropArea = cropArea
};
// Example of setting CropArea
var cropArea = new IronSoftware.Drawing.Rectangle(x: 100, y: 100, width: 300, height: 300);
var options = new BarcodeReaderOptions()
{
    CropArea = cropArea
};
Imports IronSoftware.Drawing

' Example of setting CropArea
Dim cropArea As New Rectangle(x:=100, y:=100, width:=300, height:=300)
Dim options As New BarcodeReaderOptions() With {
    .CropArea = cropArea
}
$vbLabelText   $csharpLabel

我应该指定哪种条形码类型以加快读取速度?

默认情况下,IronBarcode 中所有支持的条形码都会以图像形式扫描。 不过,如果用户知道有哪些类型的条形码或希望在图像中读取哪些类型的条形码,那么将此属性设置为只读取特定类型的条形码将大大提高读取性能和准确性,因为条形码阅读器无需遍历条形码集合来解释和读取条形码。

要使用此属性,只需将ExpectBarcodeTypes设置为BarcodeEncoding枚举的某个字段即可。 以下是IronBarcode支持的每种条形码类型的示例。

// Example: Expect only QR codes and Code128
var options = new BarcodeReaderOptions()
{
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128
};
// Example: Expect only QR codes and Code128
var options = new BarcodeReaderOptions()
{
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128
};
' Example: Expect only QR codes and Code128
Dim options As New BarcodeReaderOptions() With {
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128
}
$vbLabelText   $csharpLabel

以下是条形码类型列表,以及前面提供的示例和解释。

何时应禁用多条形码读取?

IronBarcode 默认会扫描图像中所有可用的条形码,包括扫描整个图像文件并将读取的条形码值添加到字符串数组中。 但是,如果用户不希望读取图像文件中的多个条形码,用户可以将此属性设置为false ,这样条形码读取器在找到条形码值后就会停止扫描。 这将再次提高 IronBarcode 的性能和读取速度。 有关读取多个条形码的更多信息,请参阅我们的专用指南。

图像过滤器如何提高条形码识别能力?

BarcodeReaderOptions可以添加的属性之一是图像过滤器集合。 图像滤波器对于预处理输入到 IronBarcode 的原始图像非常重要。 要应用BarcodeReaderOptions中的图像滤镜,用户必须首先初始化并指定要使用的ImageFilter集合。 有关图像校正技术(包括过滤器应用)的全面指导,请访问我们的教程。

如何优化线程以提高性能?

IronBarcode 允许用户启用和调整并行线程执行的数量,从而提高处理速度和效率。 并行线程是指在不同的处理器核心上同时执行多个线程。 IronBarcode 中MaxParallelThread属性的默认值为 4。用户可以根据机器的性能和资源量进行调整。

我是否应该启用多线程处理?

该特性使 IronBarcode 能够并行读取多个图像。 Multithreaded的默认值为true ,因此会自动管理多个线程,以提高批量条形码读取任务的性能。

为什么要删除假阳性读数?

此属性可消除所有误报的条形码读取结果。 假阳性条形码读取是指对条形码值的错误读取,但却被识别为有效。 这可能是由于排序过程中的错误,或是条形码标签或准备过程中的错误造成的。 因此,将RemoveFalsePositive设置为 true 将消除误报的条形码读数,从而提高条形码读取准确率。 但是,如果用户为了追求性能而牺牲准确性,则将此属性设置为false会有所帮助。此属性的默认值为true

哪些扫描模式可用于不同的使用案例?

定义 IronBarcode 如何扫描和检测图像中的条形码。

-自动:读取条形码时,会自动进行图像预处理,并配置最佳的读取器选项。 为获得最佳效果和性能,建议采用此方法。

  • OnlyDetectionModel :扫描图像中的条形码,并返回其位置的Iron Software.Drawing.PointF数组。 此模式无法读取检测到的条形码; 它只返回每个条形码的位置。
  • MachineLearningScan :使用机器学习检测扫描图像中的条形码并读取它们。
  • OnlyBasicScan :读取条形码,无需机器学习检测、自动图像预处理或读取器选项配置。 This option can be used with IronBarCode.Slim alone.

阅读速度设置如何影响准确性?

顾名思义, "速度"属性使用户能够进一步优化 IronBarcode 阅读器的性能。 与RemoveFalsePositive属性类似,调整此属性会降低准确性,但会提高性能。 如需深入了解 读取速度选项,包括性能基准,请参阅我们的详细指南。它接受 ReadingSpeed 枚举,该枚举有 4 个级别,如下所示:

-速度更快:可实现最快的条形码读取速度,但会降低准确性。 该过程跳过了图像预处理,经常导致条形码结果为空。 仅当输入图像清晰锐利时才使用此设置。 -平衡建议Speed属性设置为此模式。 它通过尝试对图像进行轻微处理,使条形码区域更加清晰,从而在准确性和读取性能之间取得平衡,使条形码读取器能够检测到它。 大多数情况下,这种设置足以让 IronBarcode 读取条形码图像并产生准确的输出。 -详细:如果使用ReadingSpeed.Balanced设置无法从读取中生成条形码值,用户可以选择使用ReadingSpeed.Detailed 。 IronBarcode 将对图像进行中等处理,以进一步清晰地显示条形码区域,以便条形码阅读器能够检测到条形码。 此设置对于检测较小或不太清晰的条形码图像非常有用。

  • ExtremeDetail :由于此设置会占用大量 CPU 资源,因此最不推荐使用。 将对条形码图像进行大量处理,以便阅读器能够读取条形码。 建议用户在选择此设置之前,先对图像进行预处理/应用滤镜。

何时应使用 Code39 扩展模式?

此设置允许以扩展模式读取和解释 Code39 类型的条形码,其中将应用完整的 ASCII 字符集。 将UseCode39ExtendedMode设置为true将能够更准确地读取 Code39 条形码。

如何使用自定义选项实现高级条形码读取?

既然我们已经了解了用户可以调整的所有选项,无论是提高性能还是准确性,下面就来看看如何在代码中应用这些选项。 下面的代码片段演示了 BarcodeReaderOptions 的综合用法:

using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Linq;

// Create custom reader options
var options = new BarcodeReaderOptions()
{
    // Specify expected barcode types for better performance
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128 | BarcodeEncoding.Code39,

    // Define specific area to scan (x, y, width, height in pixels)
    CropArea = new Rectangle(100, 100, 500, 400),

    // Set reading speed to balance accuracy and performance
    Speed = ReadingSpeed.Balanced,

    // Enable multithreading for better performance
    Multithreaded = true,
    MaxParallelThreads = 4,

    // Remove false positives for accuracy
    RemoveFalsePositive = true,

    // Enable Code39 extended mode if needed
    UseCode39ExtendedMode = true,

    // Set scan mode
    ScanMode = BarcodeReaderScanMode.Auto,

    // Add image filters for better recognition
    ImageFilters = new ImageFilterCollection() { 
        new SharpenFilter(),
        new InvertFilter(),
        new ContrastFilter()
    }
};

// Read barcodes with custom options
var results = BarcodeReader.Read(@"C:\path\to\your\barcode-image.png", options);

// Process results
if (results.Any())
{
    foreach (var barcode in results)
    {
        Console.WriteLine($"Barcode Type: {barcode.BarcodeType}");
        Console.WriteLine($"Value: {barcode.Value}");
        Console.WriteLine($"Confidence: {barcode.Confidence}%");
        Console.WriteLine($"Position: X={barcode.X}, Y={barcode.Y}");
        Console.WriteLine("---");
    }
}
else
{
    Console.WriteLine("No barcodes found in the image.");
}
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Linq;

// Create custom reader options
var options = new BarcodeReaderOptions()
{
    // Specify expected barcode types for better performance
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128 | BarcodeEncoding.Code39,

    // Define specific area to scan (x, y, width, height in pixels)
    CropArea = new Rectangle(100, 100, 500, 400),

    // Set reading speed to balance accuracy and performance
    Speed = ReadingSpeed.Balanced,

    // Enable multithreading for better performance
    Multithreaded = true,
    MaxParallelThreads = 4,

    // Remove false positives for accuracy
    RemoveFalsePositive = true,

    // Enable Code39 extended mode if needed
    UseCode39ExtendedMode = true,

    // Set scan mode
    ScanMode = BarcodeReaderScanMode.Auto,

    // Add image filters for better recognition
    ImageFilters = new ImageFilterCollection() { 
        new SharpenFilter(),
        new InvertFilter(),
        new ContrastFilter()
    }
};

// Read barcodes with custom options
var results = BarcodeReader.Read(@"C:\path\to\your\barcode-image.png", options);

// Process results
if (results.Any())
{
    foreach (var barcode in results)
    {
        Console.WriteLine($"Barcode Type: {barcode.BarcodeType}");
        Console.WriteLine($"Value: {barcode.Value}");
        Console.WriteLine($"Confidence: {barcode.Confidence}%");
        Console.WriteLine($"Position: X={barcode.X}, Y={barcode.Y}");
        Console.WriteLine("---");
    }
}
else
{
    Console.WriteLine("No barcodes found in the image.");
}
Imports IronBarCode
Imports IronSoftware.Drawing
Imports System
Imports System.Linq

' Create custom reader options
Dim options As New BarcodeReaderOptions() With {
    ' Specify expected barcode types for better performance
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128 Or BarcodeEncoding.Code39,

    ' Define specific area to scan (x, y, width, height in pixels)
    .CropArea = New Rectangle(100, 100, 500, 400),

    ' Set reading speed to balance accuracy and performance
    .Speed = ReadingSpeed.Balanced,

    ' Enable multithreading for better performance
    .Multithreaded = True,
    .MaxParallelThreads = 4,

    ' Remove false positives for accuracy
    .RemoveFalsePositive = True,

    ' Enable Code39 extended mode if needed
    .UseCode39ExtendedMode = True,

    ' Set scan mode
    .ScanMode = BarcodeReaderScanMode.Auto,

    ' Add image filters for better recognition
    .ImageFilters = New ImageFilterCollection() From {
        New SharpenFilter(),
        New InvertFilter(),
        New ContrastFilter()
    }
}

' Read barcodes with custom options
Dim results = BarcodeReader.Read("C:\path\to\your\barcode-image.png", options)

' Process results
If results.Any() Then
    For Each barcode In results
        Console.WriteLine($"Barcode Type: {barcode.BarcodeType}")
        Console.WriteLine($"Value: {barcode.Value}")
        Console.WriteLine($"Confidence: {barcode.Confidence}%")
        Console.WriteLine($"Position: X={barcode.X}, Y={barcode.Y}")
        Console.WriteLine("---")
    Next
Else
    Console.WriteLine("No barcodes found in the image.")
End If
$vbLabelText   $csharpLabel

从代码片段中我们可以看出,要使用BarcodeReaderOptions我们必须先对其进行初始化,然后根据上面所述的属性确定并调整BarcodeReaderOptions的属性。 初始化后的BarcodeReaderOptions可以与图像文件一起作为参数传递给BarcodeReader.Read()方法。这样,在从图像中读取条形码时, BarcodeReaderOptions中的所有设置都会被应用。

如果您遇到条形码无法识别的问题,我们的故障排除指南提供了常见问题的解决方案和提高条形码扫描准确性的技巧。

常见问题解答

C# 中的条形码读取支持哪些图像格式?

IronBarcode 支持从多种图像格式读取条形码,包括 SVG(可缩放矢量图形)、JPEG、PNG、GIF、TIFF(标记图像文件格式)和 BMP(位图图像文件)。这种全面的格式支持由 IronDrawing 提供,可实现从各种图像类型中无缝提取条形码。

如何仅用一行代码从图像文件中读取 BarCode?

使用 IronBarcode,您只需一行代码就能从图像中读取条形码:`var results = IronBarcode.BarcodeReader.Read("path/to/image.png");`.此简单方法调用可自动检测并提取 PNG、JPEG、GIF、BMP 和 TIFF 文件中的条码数据,无需任何复杂设置。

我能否指定在读取图像时要查找哪些类型的 BarCode?

是的,IronBarcode 允许您使用 BarcodeReaderOptions 中的 ExpectBarcodeTypes 属性指定条码类型。这种有针对性的方法通过只关注您期望在图像中找到的条码格式来提高读取性能。

是否可以从图像中的特定区域读取 BarCode?

当然可以!IronBarcode 提供的 CropArea 属性允许您在图像中指定条形码所在的特定区域。该功能对于大图像或当您知道条形码的大致位置时特别有用,可大大提高处理速度。

如何配置高级阅读设置以提高准确性?

IronBarcode 提供 BarcodeReaderOptions 类来配置高级读取设置。其中包括自定义条码检测灵敏度、图像预处理和其他参数的选项,这些参数可在处理具有挑战性的图像或特定条码类型时提高准确性。

是什么让 C# 开发人员从图像中读取 BarCode 变得简单?

IronBarcode 通过提供 BarcodeReader.Read() 方法简化了条形码读取,该方法开箱即用,支持多种图像格式。开发人员只需将文件名或文件路径指定为参数,即可将条形码读取功能直接集成到任何 C# 应用程序中。

Hairil Hasyimi Bin Omar
软件工程师
如所有伟大的工程师一般,Hairil 是个热心的学习者。他正在提高对 C#、Python 和 Java 的知识,并利用这些知识为 Iron Software 团队成员增值。Hairil 从马来西亚的玛拉工业大学加入 Iron Software 团队,获得化学与工艺工程学士学位。
准备开始了吗?
Nuget 下载 2,070,733 | 版本: 2026.2 刚刚发布