Linux/Docker 中使用 System.Drawing.Common 踩坑小计

前言

在项目迁移到 .net core 上面后,我们可以使用 System.Drawing.Common 组件来操作 Image,Bitmap 类型,实现生成验证码、二维码,图片操作等功能。System.Drawing.Common 组件它是依赖于 GDI+ 的,然后在 Linux 上并没有 GDI+,面向谷歌编程之后发现,Mono 团队使用 C语言 实现了GDI+ 接口,提供对非Windows系统的 GDI+ 接口访问能力,这个应该就是libgdiplus。所以想让代码在 linux 上稳定运行有关 System.Drawing.Common 的代码的时候,必须安装组件libgdiplus。而现在大多是 docker 进行发布,如果快速简单的安装 libgdiplus

安装 libgdiplus

方案一

基于微软提供的 mcr.microsoft.com/dotnet/core/aspnet:3.1 重新构建一个带libgdiplus 的镜像,但是带来的问题是,将来版本更新了,都得重新构建一遍。当然写脚本自动构建,那就没问题了。哈哈

方案二

这也是我目前采用的,构建应用镜像的时候安装 libgdiplus,但是因为系统镜像源是国外,导致安装 libgdiplus 十分缓慢,不忍直视。我们把系统包源地址修改成阿里云包源地址,问题就迎刃而解了。 参考 Dockerfile 如下:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
RUN sed -i "s@http://deb.debian.org@http://mirrors.aliyun.com@g" /etc/apt/sources.list 
RUN apt-get update -y && apt-get install -y libgdiplus && apt-get clean && ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll
ARG PROJECT
WORKDIR /app
...

替换包源地址,注意哦,官方镜像使用的是 debian 而不是 ubuntu 的源,一开始我一直以为 ubuntu 搞半天没成功。

sed -i "s@http://deb.debian.org@http://mirrors.aliyun.com@g" /etc/apt/sources.list

番外:缺少中文字体咋办呢?好办

除了遭遇以上问题外,还遇到了字体缺失,导致的生成图片中有关中文字体全部是乱码的情况,这里的中文是指我们通过程序自己画上去的。对于这个问题嘛?缺啥补啥呗,缺字体补字体。基于上面的 Dockerfile 调整:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
RUN sed -i "s@http://deb.debian.org@http://mirrors.aliyun.com@g" /etc/apt/sources.list 
RUN apt-get update -y && apt-get install -y libgdiplus locales fontconfig && apt-get clean && ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll
RUN sed -ie 's/# zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/g' /etc/locale.gen && locale-gen && mkdir /usr/share/fonts/truetype/deng/
ADD ./fonts/* /usr/share/fonts/truetype/deng/
RUN fc-cache -vf && fc-list
ENV LANG zh_CN.UTF-8
ARG PROJECT
WORKDIR /app
...
posted @ 2020-07-20 20:28  ohyex  阅读(2010)  评论(3编辑  收藏  举报