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

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

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

  1. 在 .NET6 和 .NET7 上,无法在 Linux 和 MacOS 平台实现 System.drawing.common

  2. 获取异常消息:“system.drawing.common在此平台上不受支持”。

  3. System.Drawing.EnableUnixSupport运行时配置设置为true适用于.NET6

  4. .NET7中也不再提供支持。

  5. 使用 IronSoftware.Drawing 开源库替换 NET7 的 System.Drawing.Common

    在.NET6和.NET7中,Microsoft已停止支持Linux和MacOs,并且System.Drawing.Common 只能在 Windows 上运行.

    • 在非Windows操作系统上,会抛出TypeInitializationException异常,并且PlatformNotSupportedException作为内部异常。
    • 在 .NET 6 中,当引用代码为非 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发布了System.Drawing.Common的开源替代品,名为IronSoftware.Drawing。 [NuGet] [GitHub]

要了解更多信息:https://ironsoftware.com/open-source/csharp/drawing/docs/