【问题标题】:Graphics generation in csharp with Graphics.DrawString renders different, depending on platform. (GDI)使用 Graphics.DrawString 在 csharp 中生成的图形呈现不同,具体取决于平台。 (GDI)
【发布时间】:2022-01-19 15:06:04
【问题描述】:

对于一个比利时体育社区项目,在 ASP.Net Core 中构建,我正在用 C# 动态渲染图像。图片是基于一个“基础图片”,我在其中动态添加Text,然后将图片返回给客户端。

效果很好,我对结果很满意。

但是,当我比较在我的开发环境(MacOS)上生成的客户端图像时,与我的生产环境(Azure 平台中的 Linux VM)相比,该图像渲染得更漂亮。

作为比较,你可以看到两张图片,当你看文字时,你会看到不同之处。在第二张图片中,文本字符串看起来更加像素化。

我能做些什么来避免这种情况吗?这可能与 GPU 的(不)可用性有关吗?

欢迎任何见解。

(我还将 Nuget 包 runtime.osx.10.10-x64.CoreCompat.System.Drawing 添加到我的项目中,这是在我的 MacOS 上成功运行所必需的)

供参考:相关代码sn-p:

public async Task<byte[]> CreateImageAsync(YearReview summary)
{
    var fonts = new PrivateFontCollection();
    fonts.AddFontFile(Path.Combine(_hostingEnvironment.WebRootPath, "fonts/bold.ttf"));
    fonts.AddFontFile(Path.Combine(_hostingEnvironment.WebRootPath, "fonts/light.otf"));
    var boldFont = fonts.Families[0];
    var lightFont = fonts.Families[1];

    var assembly = Assembly.GetAssembly(typeof(YearImageGenerator));
    var resourceName = "CotacolApp.StaticData.year-a.png";
    // Leaving out some variable/constants, irrelevant to the sample
    await using (var stream = assembly.GetManifestResourceStream(resourceName))
    {
        var bitmap = new Bitmap(stream);
        using (var gfx = Graphics.FromImage(bitmap))
        {
                using (Font f = new Font(boldFont, 58, FontStyle.Bold, GraphicsUnit.Pixel))
                {
                    gfx.DrawString($"{summary?.UniqueColsInYear.Number()}", f, Brushes.Black,
                        new RectangleF(0, startHeightYear, yearValuesRightBorder, 100f), rightAlignFormat);
                }
        }

        using (var imgStream = new MemoryStream())
        {
            bitmap.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png);
            return imgStream.ToArray();
        }
    }
}

如果比较图片,看左边的黑色数字,右边的黑色文字。

在开发环境(MacOS)上渲染的图片:

图片,在 Azure 云中渲染:

【问题讨论】:

  • GDI+ 是特定于 Windows 的技术。 System.Drawing 在另一个平台上的任何实现都可能使用该平台的本机绘图功能(或类似skia 的库,它可能反过来调用本机的东西)。因此,平台之间可能总是存在差异。保证像素完美一致性的最佳方法是使用像 ImageSharp 这样的纯 .NET 解决方案。
  • 不要使用System.Drawing。 Microsoft 本身对此in the documentation 发出警告。它存在于 .NET Core 中只是为了兼容
  • 我添加了一个使用 ImageSharp 的示例

标签: c# azure asp.net-core gdi


【解决方案1】:

不要使用System.Drawing。 Microsoft 本身对此in the documentation 提出了警告。它存在于 .NET Core 中只是为了兼容

在 .NET 6 及更高版本中,包含此类型的 System.Drawing.Common 包仅在 Windows 操作系统上受支持。在跨平台应用程序中使用这种类型会导致编译时警告和运行时异常。欲了解更多信息,请参阅System.Drawing.Common only supported on Windows.

链接的文章解释了问题所在,并提供了几个跨平台替代方案,例如 ImageSharp 和 SkiaSharp。

System.Drawing 的主要工作是在屏幕上绘制 UI,而不是处理图像。在 Windows 上,它只是 GDI+ 的一个非常薄的包装器。等效的跨平台技术是 MAUI,尚未发布。

ImageSharp 中的等效代码可能是:

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.Fonts;
...
//Load the fonts
FontCollection fonts = new FontCollection();
var boldPath = Path.Combine(_hostingEnvironment.WebRootPath, "fonts/bold.ttf");
var lightPath = Path.Combine(_hostingEnvironment.WebRootPath, "fonts/light.ttf");
var boldFont = fonts.Install(boldPath);
var lightFont = fonts.Install(lightPath);

//Load the image
var image = await Image.LoadAsync(stream);

//Draw the text
string yourText = $"{summary?.UniqueColsInYear.Number()}";

Font font = boldFont.CreateFont(58, FontStyle.Bold);

DrawingOptions options = new DrawingOptions()
{
    TextOptions = new TextOptions
    {
        WrapTextWidth = yearValuesRightBorder,
        HorizontalAlignment = HorizontalAlignment.Right
    }
};

var point = PointF(0, startHeightYear);
image.Mutate(x => x.DrawText(options, yourText, font, Color.Black, point));

//Save as PNG to a buffer
using var ms = new MemoryStream();
await image.SaveAsPngAsync(ms);
return ms.ToArray();

您可以查看文档中的Getting Started section。 SaveAsPngAsync is a convenience extension method。 Drawing Text 展示了如何在图像上绘制文本,Fonts 部分展示了如何处理字体。

【讨论】:

  • 谢谢,帕纳吉奥蒂斯!非常感激。我只是在尝试上述方法,但您的示例和我为 Fonts 获得的 Nuget 包(1.0.0-beta15)之间可能存在 API 更改。 FontCollection.Add 似乎在那里不存在。或者我错过了什么
  • 糟糕。请改用Install。
  • 您好,我在编辑您的答案时更新了代码,以与最新的 nuget 包及其文档保持一致。谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多