How to Read Barcodes From System.Drawing in C#
IronBarcode enables reading barcodes from System.Drawing objects on all operating systems by automatically converting them to AnyBitmap through IronDrawing, solving Microsoft's Windows-only limitation for System.Drawing support.
Introduction
System.Drawing objects are widely used in .NET for image processing tasks. However, Microsoft has discontinued support for System.Drawing on MacOS and Linux, now exclusively supporting Windows. This change has created issues for developers using IronBarcode on non-Windows operating systems, since working with barcodes typically involves graphics, images, and fonts.
To address this problem, we introduced IronDrawing. This free and open-source library, created by Iron Software, simplifies cross-platform support and provides a seamless experience. When you install IronBarcode from NuGet, IronDrawing is automatically included in your project.
For developers new to barcode reading, see our comprehensive Reading Barcodes Tutorial covering fundamental concepts and basic usage patterns. If you're working with various image formats, our guide on reading barcodes from images provides additional context and examples.
Quickstart: Read a barcode usingAnyBitmap in one easy line
This snippet shows how IronBarcode reads barcodes by creating a System.Drawing.Bitmap and letting IronDrawing implicitly cast it to AnyBitmap. With just one line, developers on any OS get fast results.
-
1Install IronBarcode with NuGet Package Manager
-
2Copy and run this code snippet.
var results = IronBarCode.BarcodeReader.Read((AnyBitmap)(new System.Drawing.Bitmap("yourImage.png")));C# -
3Deploy to test on your live environment
Start using IronBarcode in your project today with a free trial
Minimal Workflow (5 steps)
- Download the C# library for reading barcodes from
System.Drawing - Utilize
IronDrawingto castSystem.Drawingobjects intoAnyBitmap - Use the
Readmethod to read barcodes fromAnyBitmapobjects - Display the detected barcode values on the console
- Explore another article to learn how
IronDrawingis used for handling color and fonts
How Do I Cast System.Drawing Objects to AnyBitmap?
Reading barcodes from System.Drawing requires casting the object to AnyBitmap. IronDrawing was designed for ease of use and supports implicit casting for image objects from System.Drawing into IronSoftware.Drawing image objects called AnyBitmap.
Beyond System.Drawing objects, we support casting from other types:
System.Drawing.BitmapSystem.Drawing.ImageSkiaSharp.SKBitmapSkiaSharp.SKImageSixLabors.ImageSharp
See this code example for casting the above objects. Below demonstrates casting barcode images from System.Drawing objects into IronSoftware.Drawing.AnyBitmap:
Which System.Drawing Types Can Be Cast?
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)This code demonstrates seamless integration between System.Drawing objects and IronBarcode through IronDrawing. This compatibility extends across various barcode formats, detailed in our supported barcode formats guide, including QR codes, Code 128, Code 39, and many others.
Why Does Implicit Casting Work?
In the code above, we loaded two barcode images as System.Drawing.Bitmap and System.Drawing.Image. We then implicitly cast them into AnyBitmap by assigning them to AnyBitmap objects, then added these objects to an AnyBitmap list.
IronDrawing's implicit casting mechanism uses operator overloading, providing transparent conversion between System.Drawing types and AnyBitmap. This design pattern lets developers maintain existing code while gaining cross-platform compatibility. The conversion preserves all image properties including resolution, color depth, and pixel data, ensuring no quality loss.
When Should I Use Explicit vs Implicit Casting?
While implicit casting provides convenience, explicit casting might be preferred in some scenarios:
// 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 IfWhat Are Common Casting Errors?
When converting System.Drawing to AnyBitmap, developers might encounter:
- Null Reference Exceptions: Verify your
System.Drawingobject isn't null before casting - Unsupported Format Exceptions: Some exotic image formats require pre-conversion
- Memory Issues: Large images need proper disposal patterns
For troubleshooting casting issues, our troubleshooting guide provides solutions to common problems during barcode recognition.
How Do I Read Barcodes from AnyBitmap Objects?
IronBarcode accepts IronSoftware.Drawing.AnyBitmap objects in all methods without additional configuration. This simplifies development when using System.Drawing objects on non-Windows operating systems. The following code demonstrates this:
What Methods Accept AnyBitmap Parameters?
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
NextBeyond the basic Read method, IronBarcode provides several methods accepting AnyBitmap parameters. For advanced scenarios, see our guide on reading multiple barcodes demonstrating efficient processing of multiple barcodes in a single image:
// 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);
How Do I Handle Multiple Barcode Results?
The code above extends the previous example. After populating the AnyBitmap list, we iterated through it and called the Read method on each AnyBitmap object, which returned IronBarcode.BarcodeResults. We then iterated through the results to print barcode values to the console.
When handling multiple barcodes, leverage parallel processing for better performance:
// 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}")
NextWhat Other IronDrawing Features Can I Use?
IronSoftware.Drawing functionality extends beyond casting images. It handles image processing aspects like colors and fonts useful for styling barcodes and QR codes. Explore how we utilize IronDrawing to customize and add logos to QR codes.
IronDrawing provides powerful image manipulation capabilities complementing barcode processing:
// 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)For scenarios requiring specific image corrections, our image correction guide details using filters to enhance barcode readability.
Why Choose IronDrawing Over System.Drawing?
IronDrawing offers compelling advantages over System.Drawing:
- Cross-Platform Support: Works seamlessly on Windows, Linux, and macOS unlike
System.Drawing(Windows-only in .NET Core/5+) - Modern Architecture: Built on
SkiaSharpandImageSharpfor better performance and memory management - Simplified API: Maintains familiar
System.Drawing-like interfaces while adding modern conveniences - Active Development: Regular updates and improvements, unlike
System.Drawingin maintenance mode - Better Integration: Designed specifically for optimal performance with Iron Software products
For deployment considerations, especially for cloud environments, see our guides on deploying to Azure and deploying to AWS which include specific notes about cross-platform compatibility using IronDrawing.
Whether building desktop applications, web services, or cloud-native solutions, IronDrawing ensures your barcode processing code remains portable and efficient across all platforms, making it the ideal choice for modern .NET development.
Frequently Asked Questions
What is IronDrawing, and why should I use it?
IronDrawing is an open-source library by Iron Software that allows seamless conversion of System.Drawing objects into AnyBitmap, solving the Windows-only limitation of System.Drawing support. It is essential for developers aiming to read barcodes cross-platform in C#.
How does IronBarcode read barcodes from System.Drawing?
IronBarcode reads barcodes by converting System.Drawing objects to AnyBitmap using IronDrawing. This process allows cross-platform barcode reading in C#.
Can IronBarcode work on macOS and Linux?
Yes, IronBarcode can work on macOS and Linux by using IronDrawing to convert System.Drawing objects to AnyBitmap for cross-platform compatibility.
What are the benefits of using IronDrawing over System.Drawing?
IronDrawing offers cross-platform support, a modern architecture built on SkiaSharp and ImageSharp, simplified APIs, and ongoing development, unlike System.Drawing, which is Windows-only and in maintenance mode.
How do I convert a System.Drawing.Bitmap to AnyBitmap?
To convert a System.Drawing.Bitmap to AnyBitmap, you can use the implicit casting feature provided by IronDrawing, which allows seamless conversion to AnyBitmap.
What types of barcodes can IronBarcode read?
IronBarcode supports a variety of barcode formats, including QR codes, Code 128, Code 39, and more, as detailed in the supported barcode formats guide.
Is IronDrawing included when I install IronBarcode?
Yes, when you install IronBarcode from NuGet, IronDrawing is automatically included, ensuring seamless integration for cross-platform barcode scanning.
How do I handle multiple barcodes in a single image using IronBarcode?
Use the BarcodeReader.Read method with AnyBitmap, and leverage parallel processing to efficiently handle and read multiple barcodes in a single image.
What image processing features does IronDrawing provide?
IronDrawing can handle image processing tasks such as color adjustment and font handling, which are useful when styling barcodes and QR codes.
How does implicit casting help in cross-platform development?
Implicit casting in IronDrawing allows developers to convert System.Drawing objects to AnyBitmap without changing existing code, facilitating cross-platform compatibility and development for Linux, macOS, and Windows.
