How to Read Barcodes From System Drawing Objects

如何在 C# 中从System.Drawing读取条形码

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

IronBarcode 可通过 IronDrawing 自动将 AnyBitmap 转换为 System.Drawing 对象,从而在所有操作系统上读取 System.Drawing 对象中的条形码,解决了 Microsoft 对 System.Drawing 支持仅限 Windows 的限制。

简介

<! -- 待办事项:在此处添加图片 --> <! --介绍实现的示意图 --> <!--说明:说明代码概念的图表或截图 -->

System.Drawing 对象在 .NET 中广泛用于图像处理任务。 然而,Microsoft 已停止在MacOSLinux上对System.Drawing的支持,现在仅支持Windows。 这一变化给在非 Windows 操作系统上使用 IronBarcode 的开发人员带来了问题,因为处理条形码通常涉及 图形图像字体

为了解决这个问题,我们引入了IronDrawing。 这个由 IronSoftware 创建的免费开源库简化了跨平台支持并提供了无缝体验。 当您从 NuGet 安装 IronBarcode 时,IronDrawing 会自动包含在您的项目中。

对于刚刚接触条形码阅读的开发人员,请参阅我们全面的 阅读条形码教程,其中涵盖基本概念和基本使用模式。 如果您正在使用各种图像格式,我们的从图像中读取 BarCode 指南提供了更多的上下文和示例。

as-heading:2(快速入门:使用 AnyBitmap 一行轻松读取条形码)

该代码段展示了 IronBarcode 如何通过创建一个 System.Drawing.Bitmap 并让 IronDrawing 将其隐式地转换为 AnyBitmap 来读取条形码。 只需一行,任何操作系统上的开发人员都能快速获得结果。

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

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

    PM > Install-Package BarCode

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

    var results = IronBarCode.BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png")));
  3. 部署到您的生产环境中进行测试

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

如何将 System.Drawing 对象铸造为 AnyBitmap?

<! -- 待办事项:在此处添加图片 --> <! -- 说明 cast system.drawing to anybitmap 实现的示意图 --> <!--说明:说明代码概念的图表或截图 -->

System.Drawing 中读取条形码需要将对象铸入 AnyBitmap 中。 IronDrawing是为易于使用而设计的,它支持将图像对象从System.Drawing隐式转换为名为AnyBitmapIronSoftware.Drawing图像对象。

除了System.Drawing对象外,我们还支持从其他类型铸造:

  • System.Drawing.Bitmap
  • System.Drawing.Image
  • SkiaSharp.SKBitmap
  • SkiaSharp.SKImage
  • SixLabors.ImageSharp

请参阅此代码示例来铸造上述对象。 下面演示了将 System.Drawing 对象中的条形码图像转换为 IronSoftware.Drawing.AnyBitmap 对象:

哪些 System.Drawing 类型可以被套用?

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-cast-to-anybitmap.cs
using IronSoftware.Drawing;
using System.Collections.Generic;

List<AnyBitmap> barcodes = new List<AnyBitmap>();

// Instantiate System.Drawing.Bitmap
System.Drawing.Bitmap bitmapFromBitmap = new System.Drawing.Bitmap("test1.jpg");

// Cast from System.Drawing.Bitmap to AnyBitmap
AnyBitmap barcode1 = bitmapFromBitmap;

barcodes.Add(barcode1);

// Instantiate System.Drawing.Bitmap
System.Drawing.Image bitmapFromFile = System.Drawing.Image.FromFile("test2.png");

// Cast from System.Drawing.Image to AnyBitmap
AnyBitmap barcode2 = bitmapFromFile;

barcodes.Add(barcode2);
Imports IronSoftware.Drawing
Imports System.Collections.Generic

Private barcodes As New List(Of AnyBitmap)()

' Instantiate System.Drawing.Bitmap
Private bitmapFromBitmap As New System.Drawing.Bitmap("test1.jpg")

' Cast from System.Drawing.Bitmap to AnyBitmap
Private barcode1 As AnyBitmap = bitmapFromBitmap

barcodes.Add(barcode1)

' Instantiate System.Drawing.Bitmap
Dim bitmapFromFile As System.Drawing.Image = System.Drawing.Image.FromFile("test2.png")

' Cast from System.Drawing.Image to AnyBitmap
Dim barcode2 As AnyBitmap = bitmapFromFile

barcodes.Add(barcode2)
$vbLabelText   $csharpLabel

本代码通过 IronDrawing 演示了 System.Drawing 对象和 IronBarcode 之间的无缝集成。 这种兼容性适用于各种条形码格式,详见我们的支持的条形码格式指南,包括 QR 码、Code 128、Code 39 和许多其他条形码格式。

隐式铸造为何有效?

在上面的代码中,我们以 System.Drawing.BitmapSystem.Drawing.Image 的方式加载了两个条形码图像。 然后,我们通过将它们赋值给 AnyBitmap 对象,隐式地将它们转换为 AnyBitmap 对象,然后将这些对象添加到 AnyBitmap 列表中。

IronDrawing 的隐式铸造机制使用操作符重载,提供 System.Drawing 类型和 AnyBitmap 之间的透明转换。 这种设计模式可以让开发人员维护现有代码,同时获得跨平台兼容性。 转换时要保留所有图像属性,包括分辨率、色深和像素数据,确保无质量损失。

何时应使用显式铸造与隐式铸造?

虽然隐式转换提供了便利,但在某些情况下显式转换可能更受欢迎:

// Implicit casting - clean and simple for straightforward conversions
System.Drawing.Bitmap systemBitmap = new System.Drawing.Bitmap("barcode.png");
AnyBitmap anyBitmap = systemBitmap; // Implicit cast

// Explicit casting - useful when type clarity is important
System.Drawing.Image systemImage = System.Drawing.Image.FromFile("qrcode.jpg");
AnyBitmap explicitBitmap = (AnyBitmap)systemImage; // Explicit cast

// When working with nullable types or conditional logic
System.Drawing.Bitmap? nullableBitmap = GetBitmapFromSource();
if (nullableBitmap != null)
{
    AnyBitmap result = (AnyBitmap)nullableBitmap; // Explicit cast for clarity
    // Process the barcode
}
// Implicit casting - clean and simple for straightforward conversions
System.Drawing.Bitmap systemBitmap = new System.Drawing.Bitmap("barcode.png");
AnyBitmap anyBitmap = systemBitmap; // Implicit cast

// Explicit casting - useful when type clarity is important
System.Drawing.Image systemImage = System.Drawing.Image.FromFile("qrcode.jpg");
AnyBitmap explicitBitmap = (AnyBitmap)systemImage; // Explicit cast

// When working with nullable types or conditional logic
System.Drawing.Bitmap? nullableBitmap = GetBitmapFromSource();
if (nullableBitmap != null)
{
    AnyBitmap result = (AnyBitmap)nullableBitmap; // Explicit cast for clarity
    // Process the barcode
}
Imports System.Drawing

' Implicit casting - clean and simple for straightforward conversions
Dim systemBitmap As New Bitmap("barcode.png")
Dim anyBitmap As AnyBitmap = systemBitmap ' Implicit cast

' Explicit casting - useful when type clarity is important
Dim systemImage As Image = Image.FromFile("qrcode.jpg")
Dim explicitBitmap As AnyBitmap = CType(systemImage, AnyBitmap) ' Explicit cast

' When working with nullable types or conditional logic
Dim nullableBitmap As Bitmap = GetBitmapFromSource()
If nullableBitmap IsNot Nothing Then
    Dim result As AnyBitmap = CType(nullableBitmap, AnyBitmap) ' Explicit cast for clarity
    ' Process the barcode
End If
$vbLabelText   $csharpLabel

哪些是常见的铸造错误?

在将 System.Drawing 转换为 AnyBitmap 时,开发人员可能会遇到以下问题:

1.空引用异常:在转换之前验证您的 System.Drawing 对象是否为空 2.不支持的格式异常:某些特殊的图像格式需要预先转换。 3.内存问题:大图片需要适当的处理模式

对于铸造问题的故障排除,我们的故障排除指南提供了条形码识别过程中常见问题的解决方案。

如何从 AnyBitmap 对象中读取条形码?

<! -- 待办事项:在此处添加图片 --> <! -- 从 anybitmap 实现读取条形码的示意图 --> <!--说明:说明代码概念的图表或截图 -->

IronBarcode 在所有方法中都接受 IronSoftware.Drawing.AnyBitmap对象,无需额外配置。 这将简化在非 Windows 操作系统上使用 System.Drawing 对象时的开发工作。 以下代码演示了这一点:

哪些方法接受 AnyBitmap 参数?

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-system-drawing-read-anybitmap.cs
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;

List<AnyBitmap> barcodes = new List<AnyBitmap>();

System.Drawing.Bitmap bitmapFromBitmap = new System.Drawing.Bitmap("test1.jpg");
AnyBitmap barcode1 = bitmapFromBitmap;
barcodes.Add(barcode1);

System.Drawing.Image bitmapFromFile = System.Drawing.Image.FromFile("test2.png");
AnyBitmap barcode2 = bitmapFromFile;
barcodes.Add(barcode2);

foreach (var barcode in barcodes)
{
    // Read the barcode
    var results = BarcodeReader.Read(barcode);
    foreach (var result in results)
    {
        // Output the detected barcode value
        Console.WriteLine(result.Value);
    }
}
Imports IronBarCode
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic

Private barcodes As New List(Of AnyBitmap)()

Private bitmapFromBitmap As New System.Drawing.Bitmap("test1.jpg")
Private barcode1 As AnyBitmap = bitmapFromBitmap
barcodes.Add(barcode1)

Dim bitmapFromFile As System.Drawing.Image = System.Drawing.Image.FromFile("test2.png")
Dim barcode2 As AnyBitmap = bitmapFromFile
barcodes.Add(barcode2)

For Each barcode In barcodes
	' Read the barcode
	Dim results = BarcodeReader.Read(barcode)
	For Each result In results
		' Output the detected barcode value
		Console.WriteLine(result.Value)
	Next result
Next barcode
$vbLabelText   $csharpLabel

除了基本的 Read 方法外,IronBarcode 还提供了多种可接受 AnyBitmap 参数的方法。 有关高级应用场景,请参阅我们的读取多个条形码指南,该指南演示了对单个图像中多个条形码的高效处理:

// Advanced barcode reading with options
var readerOptions = new BarcodeReaderOptions
{
    // Specify barcode types to search for
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    // Enable machine learning for better accuracy
    UseML = true,
    // Set confidence threshold
    Confidence = 0.95
};

// Read with specific options
var advancedResults = BarcodeReader.Read(anyBitmap, readerOptions);
// Advanced barcode reading with options
var readerOptions = new BarcodeReaderOptions
{
    // Specify barcode types to search for
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
    // Enable machine learning for better accuracy
    UseML = true,
    // Set confidence threshold
    Confidence = 0.95
};

// Read with specific options
var advancedResults = BarcodeReader.Read(anyBitmap, readerOptions);
' Advanced barcode reading with options
Dim readerOptions As New BarcodeReaderOptions With {
    ' Specify barcode types to search for
    .ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
    ' Enable machine learning for better accuracy
    .UseML = True,
    ' Set confidence threshold
    .Confidence = 0.95
}

' Read with specific options
Dim advancedResults = BarcodeReader.Read(anyBitmap, readerOptions)
$vbLabelText   $csharpLabel

如何处理多个 BarCode 结果?

上面的代码扩展了前面的示例。 在填充 AnyBitmap 列表后,我们遍历该列表并调用每个 AnyBitmap 对象上的 Read 方法,该方法将返回 IronBarcode.BarcodeResults 。 然后,我们对结果进行迭代,将 BarCode 值打印到控制台。

处理多个 BarCode 时,利用并行处理提高性能:

// Parallel processing for multiple barcode images
var barcodeFiles = Directory.GetFiles("barcodes/", "*.png");
var allResults = new ConcurrentBag<BarcodeResult>();

Parallel.ForEach(barcodeFiles, file =>
{
    var bitmap = new System.Drawing.Bitmap(file);
    var anyBitmap = (AnyBitmap)bitmap;
    var results = BarcodeReader.Read(anyBitmap);

    foreach (var result in results)
    {
        allResults.Add(result);
    }

    bitmap.Dispose(); // Clean up resources
});

// Process all results
foreach (var result in allResults)
{
    Console.WriteLine($"Found {result.BarcodeType}: {result.Value}");
}
// Parallel processing for multiple barcode images
var barcodeFiles = Directory.GetFiles("barcodes/", "*.png");
var allResults = new ConcurrentBag<BarcodeResult>();

Parallel.ForEach(barcodeFiles, file =>
{
    var bitmap = new System.Drawing.Bitmap(file);
    var anyBitmap = (AnyBitmap)bitmap;
    var results = BarcodeReader.Read(anyBitmap);

    foreach (var result in results)
    {
        allResults.Add(result);
    }

    bitmap.Dispose(); // Clean up resources
});

// Process all results
foreach (var result in allResults)
{
    Console.WriteLine($"Found {result.BarcodeType}: {result.Value}");
}
Imports System.IO
Imports System.Collections.Concurrent
Imports System.Drawing
Imports System.Threading.Tasks

' Parallel processing for multiple barcode images
Dim barcodeFiles = Directory.GetFiles("barcodes/", "*.png")
Dim allResults = New ConcurrentBag(Of BarcodeResult)()

Parallel.ForEach(barcodeFiles, Sub(file)
                                   Dim bitmap = New Bitmap(file)
                                   Dim anyBitmap = CType(bitmap, AnyBitmap)
                                   Dim results = BarcodeReader.Read(anyBitmap)

                                   For Each result In results
                                       allResults.Add(result)
                                   Next

                                   bitmap.Dispose() ' Clean up resources
                               End Sub)

' Process all results
For Each result In allResults
    Console.WriteLine($"Found {result.BarcodeType}: {result.Value}")
Next
$vbLabelText   $csharpLabel

我还可以使用哪些 IronDrawing 功能?

IronSoftware.Drawing的功能不仅限于铸造图像。 它可以处理图像处理方面的问题,如 颜色字体,这对条形码和二维码的样式设计非常有用。 探索我们如何利用 IronDrawing自定义和添加徽标到 QR 代码

IronDrawing提供强大的图像处理功能,是对条形码处理的补充:

// Using IronDrawing for image preprocessing
using IronSoftware.Drawing;

// Load and preprocess an image before barcode reading
AnyBitmap preprocessedImage = AnyBitmap.FromFile("noisy-barcode.jpg");

// Apply image filters to improve barcode readability
preprocessedImage = preprocessedImage.ToGrayScale();
preprocessedImage = preprocessedImage.Contrast(1.5); // Increase contrast
preprocessedImage = preprocessedImage.Sharpen(); // Sharpen image

// Read the preprocessed barcode
var improvedResults = BarcodeReader.Read(preprocessedImage);
// Using IronDrawing for image preprocessing
using IronSoftware.Drawing;

// Load and preprocess an image before barcode reading
AnyBitmap preprocessedImage = AnyBitmap.FromFile("noisy-barcode.jpg");

// Apply image filters to improve barcode readability
preprocessedImage = preprocessedImage.ToGrayScale();
preprocessedImage = preprocessedImage.Contrast(1.5); // Increase contrast
preprocessedImage = preprocessedImage.Sharpen(); // Sharpen image

// Read the preprocessed barcode
var improvedResults = BarcodeReader.Read(preprocessedImage);
Imports IronSoftware.Drawing

' Load and preprocess an image before barcode reading
Dim preprocessedImage As AnyBitmap = AnyBitmap.FromFile("noisy-barcode.jpg")

' Apply image filters to improve barcode readability
preprocessedImage = preprocessedImage.ToGrayScale()
preprocessedImage = preprocessedImage.Contrast(1.5) ' Increase contrast
preprocessedImage = preprocessedImage.Sharpen() ' Sharpen image

' Read the preprocessed barcode
Dim improvedResults = BarcodeReader.Read(preprocessedImage)
$vbLabelText   $csharpLabel

对于需要进行特定图像校正的场景,我们的图像校正指南详细介绍了如何使用过滤器来增强条形码的可读性。

为什么选择 IronDrawing 而不是 System.Drawing?

IronDrawingSystem.Drawing 相比具有令人信服的优势:

1.跨平台支持:与 System.Drawing 不同(在 .NET Core/5+ 中仅支持 Windows),可在 Windows、Linux 和 macOS 上无缝运行。 2.现代架构:基于 SkiaSharpImageSharp 构建,具有更好的性能和内存管理。 3.简化的 API:保持熟悉的 System.Drawing 类接口,同时添加现代便利功能 4.积极开发:定期更新和改进,与维护模式下的 System.Drawing 不同 5.更佳的集成性:专为与 Iron Software 产品实现最佳性能而设计

有关部署注意事项,尤其是云环境,请参阅我们的部署到 Azure部署到 AWS 指南,其中包括有关使用 IronDrawing 的跨平台兼容性的具体说明。

无论是构建桌面应用程序、Web 服务还是云原生解决方案,IronDrawing 都能确保您的条形码处理代码在所有平台上保持可移植性和高效性,使其成为现代 .NET 开发的理想选择。

常见问题解答

如何在非 Windows 平台上从 System.Drawing 对象读取 BarCode?

IronBarcode 通过 IronDrawing 自动处理来自 System.Drawing 对象的跨平台条形码读取,并将其转换为 AnyBitmap 格式。这就解决了 Microsoft System.Drawing 仅限于 Windows 的限制,使您可以在 MacOS 和 Linux 系统上无缝读取条形码。

什么是 IronDrawing,为什么它包含在条形码读取中?

IronDrawing 是 Iron Software 创建的免费开源库,为图形操作提供跨平台支持。从 NuGet 安装 IronBarcode 时会自动包含该库,通过将 System.Drawing 对象转换为兼容的 AnyBitmap 格式,可以在所有操作系统上从 System.Drawing 对象读取条形码。

如何转换 System.Drawing.Bitmap 以从中读取条形码?

您可以通过简单的投向 AnyBitmap 从 System.Drawing.Bitmap 读取条形码:`var results = BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png"));`.IronBarcode 通过 IronDrawing 的隐式转换功能自动处理转换。

能否在 Linux 和 MacOS 上使用 System.Drawing 阅读 BarCode?

是的,IronBarcode 可通过 IronDrawing 从 Linux 和 MacOS 上的 System.Drawing 对象读取条形码,IronDrawing 可自动将 System.Drawing 对象转换为跨平台的 AnyBitmap 格式。这克服了微软对 System.Drawing 支持的 Windows 限制。

哪些类型的 System.Drawing 对象可用于条形码读取?

IronBarcode 支持从各种 System.Drawing 对象(包括 System.Drawing.Bitmap 和其他图像类型)读取条形码。通过 IronDrawing 的隐式铸造功能,这些对象会自动转换为 AnyBitmap,从而实现跨平台条形码扫描功能。

是否有简单的单行解决方案来从 System.Drawing 读取 BarCode?

是的,IronBarcode 提供了单行解决方案:`var results = BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png"));`.这一行创建了一个 System.Drawing.Bitmap,通过 IronDrawing 将其转换为 AnyBitmap,并读取图像中存在的所有条码。

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