c# - 是否可以选择在 .NET Standard 中使用 System.Drawing.Bitmap 而无需重写代码?

标签 c# bitmap .net-standard

这个问题在这里已经有了答案:





Cannot find Bitmap Class in Class Library (.NET Standard)

(2 个回答)


2年前关闭。




我正在尝试将我编写的代码从 .NET Framework 4.7.2 移植到 .NET Standard 2.0。本项目高度依赖System.Drawing.Bitmap用于处理图像数据的对象,主要来自 System.IO.Stream对象。
有什么方法可以让我在不重写当前使用位图的所有内容的情况下移植此代码?

我已经看过 other questions所以我知道 .NET Standard 和 Bitmap 相处得不好,但我想知道是否有解决方法可以让我在花一个月时间重写依赖于 Bitmap 的代码之前保留现有代码。 .

有问题的代码主要集中在图像编辑和处理上。这是一个应该反转图像的函数。

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;
    }
}

显然,BitmapDataBitmap抛出错误,因为它们在此上下文中不存在。

为了完整起见,这是 Visual Studio 抛出的一个示例编译器错误:
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?)

是否有任何解决方法,或者这只是直接的“您必须重写所有内容”?

最佳答案

只需安装 System.Drawing.Common NuGet 包。它具有您需要的所有功能,并且在 .NET Standard 2.0 上运行。

.NET Standard 仅提供在所有平台上共享的有限功能,这是使程序运行所需的最低要求。您可以使用之前通过 NuGet 包在 .NET Framework 中存在的许多功能。

只需在 Visual Studio NuGet 包管理器中搜索要使用的类名,就很可能会找到合适的包。

关于c# - 是否可以选择在 .NET Standard 中使用 System.Drawing.Bitmap 而无需重写代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57095208/

相关文章:

c# - 系统引用缺少 Xamarin.Forms .NetStandard

c# - 如何获取 session 响应响应的 session 请求?

.net - 为什么我无法在 .net Standard 2.0 库中使用 "SupportedOSPlatform"属性?

c# - 默认值设置为 0 的 SqlParameter 无法按预期工作

android - 将位图写入数组而不是 Android 中的文件流

bitmap - 与 RLE 位图中的字边界对齐 : contradiction in Microsoft documentation

windows - 什么是 rgbReserved?

.net-standard - AppVeyor 的 .NET Core .csproj 补丁没有任何影响

c# - .net core 3 产生与 2.2 版本不同的浮点结果

c# - 奇数/偶数 datagridview 行背景色