.NET Core:在 Docker 中的 Linux 上使用 System.Drawing.Common - “无法打开显示”错误

Shr*_*ike 7 linux x11 system.drawing .net-core

我已将代码移植到使用 System.Drawing 的 .NET Core。目前,corefx 的 System.Drawing.Common 似乎支持Linux。但是我在 Linux 上运行我的代码有困难。

特别是我得到:

NotSupportedException “无法打开显示(需要 X-Server。检查您的 DISPLAY 环境变量)”

对于此代码:

Graphics gr = Graphics.FromHwnd(IntPtr.Zero);
Run Code Online (Sandbox Code Playgroud)

以前我得到

DllNotFoundException “无法加载 DLL 'libX11':找不到指定的模块或其依赖项之一。\n(来自 HRESULT 的异常:0x8007007E)”

使用堆栈跟踪:

   at System.Drawing.LibX11Functions.XOpenDisplay(IntPtr display)
   at System.Drawing.Graphics.FromHwnd(IntPtr hwnd)
   at mycode
Run Code Online (Sandbox Code Playgroud)

但是我通过安装libx11-devpackage.json解决了这个问题。

这是我的 Dockerfile:

FROM microsoft/aspnetcore
ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE true

# install libgdiplus for System.Drawing
RUN apt-get update && \
    apt-get install -y --allow-unauthenticated libgdiplus libc6-dev

# install x11 for System.Drawing
RUN apt-get update && \
    apt-get install -y --allow-unauthenticated libx11-dev
Run Code Online (Sandbox Code Playgroud)

那么我该如何处理“无法打开显示(需要 X-Server。检查您的 DISPLAY 环境变量)”错误?

小智 1

也许,您可以使用基于图像的Graphics,而不是基于窗口的。像这样的东西:

var g = Graphics.FromImage(new Bitmap(1, 1));
Run Code Online (Sandbox Code Playgroud)