.net Core 6.0 部署到欧拉(Linux)系统上,“The type initializer for ‘Gdip‘ threw an exception” 报错的解决方案

980 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

前言

“The type initializer for 'Gdip' threw an exception” 报错的根本原因, 是因为我们使用了“System.Drawing.Common” 类库,而该类库被归为 Windows 特定的库。 在为非 Windows 操作系统编译时,会引发异常。微软官方给出的解释是:“由于 System.Drawing.Common 被设计为 Windows 技术的精简包装器,因此其跨平台实现欠佳.......”,此处省略一万字, 总结出一句话,  System.Drawing.Common linux 上不能用。

解决方案

不要慌, 虽然“System.Drawing.Common” 类库在Linux 上不能用,但是官方也给出了相应的解决方案。如下链接: 中断性变更:仅在 Windows 上支持 System.Drawing.Common - .NET | Microsoft Docs 

 可以看到, 官方给出了三个替代库,既然有替代库, 那么就好说了, 我们就随便找一个库来试试。

1、ImageSharp

由于官方给出了文档,这里就不在详细说明了, 只列出简单测试的Demo。

Demo 0积分下载地址:ImageSharp实现代码-C#文档类资源-CSDN下载

using System;
using System.Text;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

namespace imagesharp_test
{
    class Program
    {
        static void Main(string[] args)
        {
            // Image.Load(string path) is a shortcut for our default type. 
            // Other pixel formats use Image.Load<TPixel>(string path))

            using (var img = new Image<Rgba32>(210, 50, Color.White))
            {
                var image = AddMultilineText(img, "胖太乙", 20,3,15);
                image.Save("Pangtaiyi.jpg"); // Automatic encoder selected based on extension.
            }
            Console.ReadLine();
        }

        /// <summary>
        /// 多行文本输出
        /// </summary>
        /// <param name="templateImage">图片</param>
        /// <param name="text">写入文本</param>
        /// <param name="fontSize">字体大小</param>
        /// <param name="x">x坐标</param>
        /// <param name="y">y坐标</param>
        /// <returns></returns>
        public static Image AddMultilineText(Image templateImage, string text, int fontSize, int x, int y)
        {
            var fonts = new FontCollection();
            var fontFamily = fonts.Add("./simhei.ttf");
            var font = new Font(fontFamily, fontSize, FontStyle.Bold);
            templateImage.Mutate(o =>
            {
                o.DrawText(text, font, Color.Black, new PointF(x, y));
            });

            return templateImage;
        }
    }
}

在找到该解决方案之前, 我也看了很多其他的博客, 大部分都是在说在服务器上通过yum 安装 “libgdiplus” , 但是我试了很多种方式, 都没有成功, 不知道是不是因为我是用的.net 6.0的原因。