SkiaSharp.SKImageInfo threw an exception. 报错解决方法

Type initializer for 'SkiaSharp.SKImageInfo' threw an exception. 的问题,核心在于:在 Linux/容器/ 或 非 Windows/MAUI/Blazor 环境中,缺少本地 Skia 原生库(libSkiaSharp.so)导致这个异常。

Exception: 

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

 ---> System.DllNotFoundException: Unable to load DLL 'libSkiaSharp' or one of its dependencies: 找不到指定的模块。 (0x8007007E)

   at SkiaSharp.SkiaApi.sk_colortype_get_default_8888()

   at SkiaSharp.SKImageInfo..cctor()

   --- End of inner exception stack trace ---

SkiaSharp.SKImageInfo threw an exception. 报错解决方法

常见场景及解决方案

1. Linux / Docker 容器 (.NET Core/.NET 6/.NET 8)

你很可能缺少 libSkiaSharp.so,需要通过 NuGet 引入对应平台的原生包:

添加以下依赖到 .csproj:

<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.x.x" />

或者

<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.x.x" />

重建并部署后,libSkiaSharp.so 会被带入项目,Linux 上就不会再报找不到的错误了。这一点在多个用户反馈中被验证:他们加上这个包后问题立即解决。

比较好的顺序是:先安装 SkiaSharp,接着安装 SkiaSharp.NativeAssets.Linux 或 .NoDependencies,然后构建并部署。

Syncfusion、Aspose 等库引用 SkiaSharp 绘图时,也必须这样处理,否则在 Linux Docker 或 Azure、Beanstalk等平台就会报同样的错误

2. .NET MAUI / Blazor WASM 或 iOS/macOS/Android 环境

在这些平台中,不支持 SkiaSharp.NativeAssets.Linux 包。

对于 MAUI,推荐直接使用 SkiaSharp.Views 包,它会自动引入相应运行时所需的原生库。

3. Window IIS 环境

如果在Windows环境报错,确保dll文件部署到发布目录。

Exception: 

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

 ---> System.InvalidOperationException: The version of the native libSkiaSharp library (88.1) is incompatible with this version of SkiaSharp. Supported versions of the native libSkiaSharp library are in the range [119.0, 120.0).

   at SkiaSharp.SkiaSharpVersion.CheckNativeLibraryCompatible(Version minSupported, Version current, Boolean throwIfIncompatible)

   at SkiaSharp.SkiaSharpVersion.CheckNativeLibraryCompatible(Boolean throwIfIncompatible)

   at SkiaSharp.SKObject..cctor()

   --- End of inner exception stack trace ---

如果报以上错误,尝试降低SkiaSharp库的版本再发布。

总结

  • 错误原因:在非 Windows 环境丢失 libSkiaSharp.so。
  • 解决方法:引入正确平台的原生 NuGet 包。
  • Linux:SkiaSharp.NativeAssets.Linux 或 .NoDependencies。
  • MAUI:使用 SkiaSharp.Views。
  • WebAssembly:同时安装 SkiaSharp.Views.Blazor + SkiaSharp.NativeAssets.WebAssembly。
评论