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

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

從 .NET 6 開始,微軟已停止在 Linux 和 macOS 平台上支援 System.Drawing.Common。該程式庫現在僅適用於 Windows。如需更多詳情,請參考 官方文件.

避免系統不支援 system.drawing.common 的解決方法

.NET6

在非 Windows 作業系統上,會拋出帶有 PlatformNotSupportedException 作為內部異常的 TypeInitializationException。 平臺分析儀對於非 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 開始,Microsoft 完全取消了 Linux 和 macOS 上對 System.Drawing.Common 的支持,包括之前可用的替代方案。

Iron Software 發佈了一個開源來替代 System.Drawing.Common 的解決方案,名為 IronSoftware.Drawing

如需了解更多,請訪問 官方文件