如何在 C# 中从 System.Drawing 读取条形码
IronBarcode使在所有操作系统上从System.Drawing对象读取条形码成为可能,它通过IronDrawing自动将其转换为AnyBitmap,解决了Microsoft仅在Windows上支持System.Drawing的限制。
介绍
System.Drawing对象广泛用于.NET的图像处理任务。 然而,Microsoft已停止支持System.Drawing在MacOS和Linux上,现在仅支持Windows。 这一变化给在非 Windows 操作系统上使用 IronBarcode 的开发人员带来了问题,因为处理条形码通常涉及 图形、图像 和 字体。
为了解决这个问题,我们推出了IronDrawing。 这个由Iron Software创建的免费和开源库简化了跨平台支持,提供流畅的体验。 当您从NuGet安装IronBarcode时,IronDrawing会自动包含在您的项目中。
对于条形码读取新手,请参阅我们的条形码读取教程,涵盖基本概念和基本使用模式。 如果您正在处理各种图像格式,我们关于从图像中读取条形码的指南提供了额外的背景和示例。
快速入门:使用AnyBitmap读取条形码,只需一个简单的行
这个代码片段展示了IronBarcode如何通过创建System.Drawing.Bitmap并让IronDrawing隐式转换为AnyBitmap来读取条形码。 只需一行,任何操作系统上的开发人员都能快速获得结果。
-
1使用 IronBarcode 安装 NuGet Package Manager
-
2复制并运行这段代码。
var results = IronBarCode.BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png")));Dim results = IronBarCode.BarcodeReader.Read(DirectCast(New System.Drawing.Bitmap("yourImage.png"), AnyBitmap))Dim results = IronBarCode.BarcodeReader.Read(DirectCast(New System.Drawing.Bitmap("yourImage.png"), AnyBitmap)) -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronBarcode
最小工作流程(5 个步骤)
- 下载C#库以从
System.Drawing中读取条形码 - 利用
IronDrawing将System.Drawing对象转换为AnyBitmap - 使用
Read方法从AnyBitmap对象中读取条形码 - 在控制台上显示检测到的条码值
- 探索另一篇文章,了解
IronDrawing如何用于处理颜色和字体
如何将System.Drawing对象转换为AnyBitmap?
从System.Drawing读取条形码需要将对象转换为AnyBitmap。 IronDrawing设计的目的是易于使用,并支持将@@System.Drawing中的图像对象隐式转换为IronSoftware.Drawing图像对象,称为AnyBitmap。
除了System.Drawing对象,我们还支持从其他类型转换:
System.Drawing.BitmapSystem.Drawing.ImageSkiaSharp.SKBitmapSkiaSharp.SKImageSixLabors.ImageSharp
请参阅此代码示例以转换上述对象。 下面演示了如何将条形码图像从System.Drawing对象转换为IronSoftware.Drawing.AnyBitmap:
可以转化哪些System.Drawing类型?
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);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)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)此代码展示了通过IronDrawing实现System.Drawing对象与IronBarcode之间的简单集成。 这种兼容性涵盖各种条形码格式,详细信息请参阅我们的支持的条形码格式指南,包括QR码、Code 128、Code 39等。
为什么隐式转换有效?
在上面的代码中,我们将两个条形码图像加载为System.Drawing.Bitmap和System.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 IfImports 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常见的转换错误有哪些?
当将System.Drawing转换为AnyBitmap时,开发人员可能会遇到:
- 空引用异常:在转换之前核查您的
System.Drawing对象是否为空 - 不支持的格式异常:某些特殊图像格式需要预转换
- 内存问题:大型图像需要正确的内存释放模式
有关转换问题排查,请参阅我们的排查指南,提供有关条形码识别的常见问题解决方案。
如何从AnyBitmap对象读取条形码?
IronBarcode在所有方法中都接受IronSoftware.Drawing.AnyBitmap对象,无需额外配置。 在非Windows操作系统上使用System.Drawing对象时,这简化了开发。 以下代码演示了这一点:
哪些方法接受AnyBitmap参数?
using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
// Create a list of image file paths to read barcodes from
List<string> barcodeFiles = new List<string>
{
"test1.jpg",
"test2.png"
};
foreach (var barcodeFile in barcodeFiles)
{
// Read the barcode from file path
var results = BarcodeReader.Read(barcodeFile);
foreach (var result in results)
{
// Output the detected barcode value
Console.WriteLine(result.Value);
}
}using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
// Create a list of image file paths to read barcodes from
List<string> barcodeFiles = new List<string>
{
"test1.jpg",
"test2.png"
};
foreach (var barcodeFile in barcodeFiles)
{
// Read the barcode from file path
var results = BarcodeReader.Read(barcodeFile);
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
' Create a list of image file paths to read barcodes from
Dim barcodeFiles As New List(Of String) From {
"test1.jpg",
"test2.png"
}
For Each barcodeFile In barcodeFiles
' Read the barcode from file path
Dim results = BarcodeReader.Read(barcodeFile)
For Each result In results
' Output the detected barcode value
Console.WriteLine(result.Value)
Next
NextImports IronBarCode
Imports IronSoftware.Drawing
Imports System
Imports System.Collections.Generic
' Create a list of image file paths to read barcodes from
Dim barcodeFiles As New List(Of String) From {
"test1.jpg",
"test2.png"
}
For Each barcodeFile In barcodeFiles
' Read the barcode from file path
Dim results = BarcodeReader.Read(barcodeFile)
For Each result In results
' Output the detected barcode value
Console.WriteLine(result.Value)
Next
Next除了基本的Read方法,IronBarcode还提供多个接受AnyBitmap参数的方法。 对于高级场景,请参阅我们的读取多个条形码指南,演示在单个图像中高效处理多个条形码。
// Advanced barcode reading with options
var readerOptions = new BarcodeReaderOptions
{
// Specify barcode types to search for
ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
// Set confidence threshold
ConfidenceThreshold = 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,
// Set confidence threshold
ConfidenceThreshold = 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,
' Set confidence threshold
.ConfidenceThreshold = 0.95
}
' Read with specific options
Dim 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,
' Set confidence threshold
.ConfidenceThreshold = 0.95
}
' Read with specific options
Dim advancedResults = BarcodeReader.Read(anyBitmap, readerOptions)如何处理多个条形码结果?
上面的代码扩展了前面的示例。 在填充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 As New ConcurrentBag(Of BarcodeResult)()
Parallel.ForEach(barcodeFiles, Sub(file)
Dim bitmap As New Bitmap(file)
Dim anyBitmap As 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}")
NextImports 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 As New ConcurrentBag(Of BarcodeResult)()
Parallel.ForEach(barcodeFiles, Sub(file)
Dim bitmap As New Bitmap(file)
Dim anyBitmap As 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可以使用哪些其他IronDrawing功能?
IronSoftware.Drawing功能不仅限于转换图像。 它可以处理图像处理方面的问题,如 颜色和 字体,这对条形码和二维码的样式设计非常有用。 探索我们如何利用IronDrawing 定制和向QR码添加标志。
IronDrawing提供强大的图像操作能力,补充了条形码处理:
// Using IronDrawing to load the image, and IronBarcode's image filters for preprocessing
using IronBarCode;
using IronSoftware.Drawing;
// Load an image before barcode reading
AnyBitmap preprocessedImage = AnyBitmap.FromFile("noisy-barcode.jpg");
// Apply image filters to improve barcode readability
var options = new BarcodeReaderOptions
{
ImageFilters = new ImageFilterCollection
{
new ContrastFilter(1.5f), // Increase contrast
new SharpenFilter() // Sharpen image
}
};
// Read the preprocessed barcode
var improvedResults = BarcodeReader.Read(preprocessedImage, options);// Using IronDrawing to load the image, and IronBarcode's image filters for preprocessing
using IronBarCode;
using IronSoftware.Drawing;
// Load an image before barcode reading
AnyBitmap preprocessedImage = AnyBitmap.FromFile("noisy-barcode.jpg");
// Apply image filters to improve barcode readability
var options = new BarcodeReaderOptions
{
ImageFilters = new ImageFilterCollection
{
new ContrastFilter(1.5f), // Increase contrast
new SharpenFilter() // Sharpen image
}
};
// Read the preprocessed barcode
var improvedResults = BarcodeReader.Read(preprocessedImage, options);' Using IronDrawing to load the image, and IronBarcode's image filters for preprocessing
Imports IronBarCode
Imports IronSoftware.Drawing
' Load an image before barcode reading
Dim preprocessedImage As AnyBitmap = AnyBitmap.FromFile("noisy-barcode.jpg")
' Apply image filters to improve barcode readability
Dim options As New BarcodeReaderOptions With {
.ImageFilters = New ImageFilterCollection From {
New ContrastFilter(1.5F), ' Increase contrast
New SharpenFilter() ' Sharpen image
}
}
' Read the preprocessed barcode
Dim improvedResults = BarcodeReader.Read(preprocessedImage, options)' Using IronDrawing to load the image, and IronBarcode's image filters for preprocessing
Imports IronBarCode
Imports IronSoftware.Drawing
' Load an image before barcode reading
Dim preprocessedImage As AnyBitmap = AnyBitmap.FromFile("noisy-barcode.jpg")
' Apply image filters to improve barcode readability
Dim options As New BarcodeReaderOptions With {
.ImageFilters = New ImageFilterCollection From {
New ContrastFilter(1.5F), ' Increase contrast
New SharpenFilter() ' Sharpen image
}
}
' Read the preprocessed barcode
Dim improvedResults = BarcodeReader.Read(preprocessedImage, options)对于需要特定图像校正的方案,我们的图像校正指南详述了使用滤镜增强条形码可读性。
为什么选择IronDrawing而不是System.Drawing?
IronDrawing在System.Drawing之上提供了令人信服的优势:
- 跨平台支持:可在Windows、Linux和macOS上使用,与
System.Drawing不同(仅在.NET Core/5+的Windows中) - 现代架构:基于
SkiaSharp和ImageSharp,提供更好的性能和内存管理 - 简化的API:保持类似于
System.Drawing的熟悉接口,同时加入现代的便捷功能 - 积极开发:定期更新和改进,与
System.Drawing的维护模式不同 - 更好的集成:专为与Iron Software产品的最佳性能而设计
有关部署注意事项,尤其是在云环境中,请参见我们的部署到Azure和部署到AWS指南,其中包括关于使用IronDrawing实现跨平台兼容性的具体说明。
无论是构建桌面应用程序、web服务还是云原生解决方案,IronDrawing确保您的条形码处理代码在所有平台上保持便携和高效,这使其成为现代.NET开发的理想选择。
常见问题
什么是IronDrawing,我为什么应该使用它?
IronDrawing是Iron Software推出的开源库,可以将System.Drawing对象顺利转换为AnyBitmap,解决了System.Drawing支持仅限于Windows的限制。对于希望在C#中跨平台读取条码的开发者来说,它是必不可少的。
IronBarcode如何从System.Drawing读取条码?
IronBarcode通过使用IronDrawing将System.Drawing对象转换为AnyBitmap来读取条码。此过程使得在C#中跨平台读取条码得以实现。
IronBarcode可以在macOS和Linux上运行吗?
可以,IronBarcode可以通过使用IronDrawing将System.Drawing对象转换为AnyBitmap,以实现跨平台兼容性,从而在macOS和Linux上运行。
使用IronDrawing替代System.Drawing的好处是什么?
IronDrawing提供了跨平台支持,采用基于SkiaSharp和ImageSharp的现代架构,简化的API,并且正在持续开发,而System.Drawing仅限于Windows,并处于维护状态。
如何将System.Drawing.Bitmap转换为AnyBitmap?
要将System.Drawing.Bitmap转换为AnyBitmap,您可以使用IronDrawing提供的隐式转换功能,允许顺利转换为AnyBitmap。
IronBarcode 能够读取哪些类型的条码?
IronBarcode支持多种条码格式,包括QR代码、Code 128、Code 39等,详情请参阅所支持的条码格式指南。
安装IronBarcode时会自动包含IronDrawing吗?
是的,当您从NuGet安装IronBarcode时,IronDrawing会自动包含在内,确保跨平台条码扫描的简便集成。
如何使用IronBarcode处理单个图像中的多个条码?
使用BarcodeReader.Read方法与AnyBitmap结合,并利用并行处理高效处理和读取单个图像中的多个条码。
IronDrawing提供哪些图像处理功能?
IronDrawing可以处理如颜色调整和字体处理的图像处理任务,这在样式化条码和QR代码时非常有用。
隐式转换在跨平台开发中有何帮助?
IronDrawing中的隐式转换允许开发者将System.Drawing对象转换为AnyBitmap而无需更改现有代码,从而促进Linux、macOS和Windows的跨平台兼容性和开发。