.NET Core:在 Docker 中的 Linux 上使用 System.Drawing.Common - "Could not open display" 错误

.NET Core: using System.Drawing.Common on Linux in Docker - "Could not open display" error

我已将代码移植到使用 System.Drawing 的 .NET Core 上。目前看来 System.Drawing。common from corefx supports Linux。 但是我在 Linux 上的 运行 我的代码有困难。

特别是我得到:

NotSupportedException "Could not open display (X-Server required. Check your DISPLAY environment variable)"

对于此代码:

Graphics gr = Graphics.FromHwnd(IntPtr.Zero);

之前我得到

DllNotFoundException "Unable to load DLL 'libX11': The specified module or one of its dependencies could not be found.\n (Exception from HRESULT: 0x8007007E)"

使用堆栈跟踪:

   at System.Drawing.LibX11Functions.XOpenDisplay(IntPtr display)
   at System.Drawing.Graphics.FromHwnd(IntPtr hwnd)
   at mycode

但是我通过安装 libx11-dev 包解决了这个问题。

这是我的 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

那么 "Could not open display (X-Server required. Check your DISPLAY environment variable)" 错误该怎么办?

或许,您可以使用基于图像的 Graphics,而不是基于 window 的。像这样:

var g = Graphics.FromImage(new Bitmap(1, 1));