Cross-platform System.Drawing.Bitmap in .NET 8?

678 Views Asked by At

We've been migrating a .NET 4.x application to .NET 8 and encountered a massive problem with System.Drawing.Bitmap. Our image processing was heavily dependent on graphic libraries, such as AForge. The AForge library uses System.Drawing.Bitmap and lockbits and manipulates the unmanaged memory of the Bitmap object.

My question: is there a wrapper for System.Drawing.Bitmap or is any effort being made to replicate the base functionality? Or, do any of Microsoft's suggested alternative libraries offer unmanaged (unsafe) access to the image memory that can be used with third-party libraries, such as AForge?

I understand Microsoft's movement on "a million bugs, etc., etc." with the mono implementation. But, thousands of libraries depend on basic System.Drawing.Bitmap functionality, which is only a tiny component of the whole System.Drawing namespace. It seems that the most popular components can be replicated to continue using the vast collection of libraries that people and companies have put effort into building.

Reference: https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only

1

There are 1 best solutions below

0
Mark at Datus On

Just discovered this issue tonight after upgrading System.Drawing.Common to 8x, but OP was the only question I found on the topic.

I went with SkiaSharp (the first alternative mentioned in the notification) for a drop-in replacement. It has no license restrictions, and appears to have a similar decomposition to the existing System.Drawing code that triggered the compiler warning.

[Generating a bitmap via System.Drawing: (This will apparently throw an error if not running windows post .Net 6)

  using (var ms = new MemoryStream())
  using (Image img = new Bitmap(1, 1)) {
      img.Save(ms, ImageFormat.Jpeg);
      var bytes = ms.ToArray();
      return this.File(bytes, "image/jpeg");
  }

And via SkiaSharp:

 using (var bmap = new SKBitmap(1, 1, false))
 using (var img = SKImage.FromBitmap(bmap))
 using (var bytes = img.Encode(SKEncodedImageFormat.Jpeg, 0)) {
    return this.File(bytes.ToArray(), "image/jpeg");
 }

I Hope this helps somebody.