System.Drawing.Common 替代方案(.NET 7 及非 Windows)

This article was translated from English: Does it need improvement?
Translated
View the article in English

从 .NET6 开始,Microsoft 已停止在 Linux 和 macOS 上支持 System.Drawing.Common。 此库现在只能在Windows上运行。 有关更多详细信息,请参阅官方文档

该平台不支持避免 system.drawing.common 的变通方法

#.NET6

在非 Windows 操作系统上,会抛出一个 TypeInitializationException,其内部异常为 PlatformNotSupportedException。 平台分析器会在非Windows平台上发出编译时警告。 除非您设置配置选项,否则会抛出以下运行时异常:

System.TypeInitializationException : The type initializer for 'Gdip' threw an exception.

    ---- System.PlatformNotSupportedException : System.Drawing.Common is not supported on non-Windows platforms.

.NET6 中的临时解决方案:

通过在runtimeconfig.json文件中将System.Drawing.EnableUnixSupport运行时配置开关设为true,启用对非Windows平台的支持:

{

    "runtimeOptions": {

        "configProperties": {

            "System.Drawing.EnableUnixSupport": true

        }

    }

}

在代码开头添加以下代码:

System.AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);

.NET7 及以上版本

从 .NET7 开始,微软已完全取消对 Linux 和 macOS 上 System.Drawing.Common 的支持,包括先前可用的解决方法。

Iron Software 发布了一款名为IronSoftware.Drawing的开源替代品,用于替代 System.Drawing.Common。