[Public] Workaround: Converting AnyBitmap to System.Drawing.Bitmap in .NET Framework Desktop Apps
Summary
Developers working with IronBarcode in .NET Framework desktop apps such as WinForms, users may encounter casting errors when trying to assign AnyBitmap
directly to a System.Drawing.Image
or Bitmap
. This is due to differences in implicit conversion support between .NET Framework and .NET Core/.NET 5+.
Problem Description
In .NET Framework (e.g., WinForms project targeting .NET 4.8), the following code will fail at compile time.
Use Case:
- Using IronBarCode in NET Framework Desktop Apps such as WinForm app to create a barcode and display in the picturebox that only accepts System.Drawing.Image objects
- Thrown below error during compile:
Cannot implicitly convert type 'IronSoftware.Drawing.AnyBitmap' to 'System.Drawing.Image
var myBarcode = BarcodeWriter.CreateBarcode("12345", BarcodeWriterEncoding.EAN8);
//These lines cause compile-time errors
Image myBarcodeImage = myBarcode.Image;
Bitmap myBarcodeBitmap = myBarcode.ToBitmap();
Possible Cause
The type returned by BarcodeWriter.Image
or .ToBitmap()
is IronSoftware.Drawing.AnyBitmap
, which does support implicit conversion to System.Drawing.Bitmap
or Image
— but only when using .NET 6, .NET 7, .NET 8, or higher.
In .NET Framework, implicit operators and internal type bridging do not always resolve properly, especially when types come from different libraries or compatibility layers.
Recommended Workarounds
Users can use one of the workarounds below to solve this issue
Workaround 1:
Install the Required Package
Add the System.Drawing.Common
NuGet package to your project.
.NET CLI:
dotnet add package System.Drawing.Common
Package Manager Console:
Install-Package System.Drawing.Common
.csproj (for SDK-style projects):
<PackageReference Include="System.Drawing.Common" Version="8.0.0" />
Workaround 2:
Convert AnyBitmap to Stream
Use the ToWindowsBitmapStream()
method and convert manually using a stream before adding the stream into the picturebox:
var myBarcode = BarcodeWriter.CreateBarcode("12345", BarcodeWriterEncoding.EAN8);
myBarcode.ResizeTo(400, 100); // Optional resizing
using (var ms = myBarcode.ToWindowsBitmapStream())
{
pictureBox1.Image = Image.FromStream(ms); // Works in .NET Framework
}
Why it works:
-
ToWindowsBitmapStream()
convertsAnyBitmap
to a GDI-compatible image format -
Image.FromStream
can safely parse this into a nativeSystem.Drawing.Image
Additional Notes
-
You may also convert
AnyBitmap
object to stream usingToStream()