5

I am trying to port code I have written from .NET Framework 4.7.2 to .NET Standard 2.0. This project is highly dependent on System.Drawing.Bitmap objects for processing image data, primarily from System.IO.Stream objects. Is there any way for me to port this code without rewriting everything that currently uses a Bitmap?

I've already looked at other questions so I am aware that .NET Standard and Bitmap don't get along well, but I wanted to know if there are workarounds that would let me keep existing code before I spend a month rewriting code that relies on Bitmap.

The code in question is heavily focused on image editing and processing. This is one function that is supposed to invert an image.

Bitmap bmp;

...

public void Invert()
{
    unsafe
    {
        BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadWrite, Bitmap.PixelFormat);
        int bytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(Bitmap.PixelFormat) / 8;
        int heightInPixels = bitmapData.Height;
        int widthInBytes = bitmapData.Width * bytesPerPixel;
        byte* ptrFirstPixel = (byte*)bitmapData.Scan0;

        for (int y = 0; y < heightInPixels; y++)
        {
            byte* currentLine = ptrFirstPixel + (y * bitmapData.Stride);
            for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
            {
                currentLine[x] = (byte)(255 - currentLine[x]);
                currentLine[x + 1] = (byte)(255 - currentLine[x + 1]);
                currentLine[x + 2] = (byte)(255 - currentLine[x + 2]);
            }
        }
        Bitmap.UnlockBits(bitmapData);
        PixIsActive = false;
    }
}

Obviously, BitmapData and Bitmap throw errors, as they do not exist in this context.

For the sake of completeness, this is an example compiler error Visual Studio throws:

1>XImage.cs(4,22,4,29): error CS0234: The type or namespace name 'Imaging' does not exist in the namespace 'System.Drawing' (are you missing an assembly reference?)

Is there any kind of workaround, or is this just a straight up "you have to rewrite everything"?

EagleBirdman
  • 140
  • 1
  • 10

1 Answers1

8

Simply install the System.Drawing.Common NuGet package. It has all the functionality you need, and it runs on .NET Standard 2.0.

.NET Standard only provides limited functionality that is shared across all platforms and that is the minimum required to make a program run. You can use a lot of functionality that was in the .NET Framework before through NuGet packages.

Simply search for the class name you want to use in the Visual Studio NuGet Package manager and you will most likely find the appropriate package.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325