出現問題的原因
在Linux環境部署.NET Core程序時,如果要到System.Drawing.Common引用會出現該問題,目前大量的第三方組件使用該Windows專用庫,尤其是涉及圖片處理、Word相關的組件、二維碼等
問題現象
出現相關Gdip異常,安裝相應組件后重啟項目及服務器無效,異常如下
The type initializer for 'Gdip' threw an exception.
at System.Drawing.SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(IntPtr& fontfamily)
at System.Drawing.FontFamily.GetGdipGenericSansSerif()
at System.Drawing.FontFamily.get_GenericSansSerif()
at System.Drawing.Font.CreateFont(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte charSet, Boolean isVertical)
at System.Drawing.Font..ctor(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte gdiCharSet, Boolean gdiVerticalFont)
at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth, Double MaximumWidth)
at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth)
at OfficeOpenXml.ExcelRangeBase.AutoFitColumns()
at Magicodes.ExporterAndImporter.Excel.Utility.ExportHelper`1.AddHeaderAndStyles()
at Magicodes.ExporterAndImporter.Excel.Utility.ExportHelper`1.Export(ICollection`1 dataItems)
at Magicodes.ExporterAndImporter.Excel.ExcelExporter.ExportAsByteArray[T](ICollection`1 dataItems)
解決辦法
.NET 6之前
在Linux服務器上安裝 libgdiplus 即可解決
libgdiplus
是System.Drawing.Common
原生端跨平台實現的主要提供者,是開源mono項目
安裝步驟(以Centos 7為例)
- 更新包
yum install -y epel-release
- 查找包
yum whatprovides libgdiplus # 輸出以下內容,具體以顯示為准,注意版本號 # libgdiplus-2.10-10.el7.x86_64 : An Open Source implementation of the GDI+ API.
-
- ImageSharp
- SkiaSharp
- Microsoft.Maui.Graphics安裝包
yum install -y libgdiplus-2.10-10.el7.x86_64
.NET 6及以后
由於官方不再支持在非Windows環境使用libgdiplus,需要單獨開啟運行時環境支持
處理步驟
- 按照.NET 6之前的方案安裝 libgdiplus
- runtimeconfig.json配置文件中新增
System.Drawing.EnableUnixSupport
{ "runtimeOptions": { "configProperties": { "System.Drawing.EnableUnixSupport": true } } }
構建項目時,會在輸出目錄中生成[appname].runtimeconfig.json文件,只需要修改該配置文件即可
其他建議
官方不再建議使用libgdiplus,主要是原因是libgdiplus非常臃腫、外部依賴眾多、未解決bug及異常情況難以修復,修改[appname].runtimeconfig.json只是臨時方案,需要逐步遷移到以下項目
官方參考資料:https://docs.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only