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 已發佈一個開源替代 System.Drawing.Common 的程式,名為 IronSoftware.Drawing