Docker 内JAVA用SVG代码转PNG , 图片中文乱码问题

场景:

使用JAVA的 org.apache.batik 从SVG代码生成PNG图片

public static void convertToPng(String svgCode, OutputStream outputStream){
        try {
            byte[] bytes = svgCode.getBytes("utf-8");
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
        }  catch (Exception e) {
		}finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

问题:

本地测试均好使,但是使用Docker部署后,发现生成的图片,中文是乱码的。

如图:Docker 内JAVA用SVG代码转PNG , 图片中文乱码问题_第1张图片

 

原因:

docker的centos系统内没有对应的中文字体

解决:

直接在Docker容器内操作:

#安装字体库
yum -y install fontconfig 
yum -y install ttmkfdir 
ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir 

chmod 777 /usr/share/fonts/dejavu

复制字体文件
windows里的 C:\Windows\Fonts 下的 simsun.ttc
复制到服务器的 /usr/share/fonts/dejavu


#刷新字体缓存
fc-cache 

Dockerfile直接构建的话, 脚本可以添加如下代码:

放到脚本合适的位置,可以把 安装字体库这段 拼接到Dockerfile中已有的RUN 语句后面

#复制本地字体库(fonts是Dockerfile同级目录)
COPY fonts/simsun.ttc /var/tmp/simsun.ttc


#安装字体库
	RUN yum -y install fontconfig \
	&& chmod 777 /usr/share/fonts/dejavu \
	&& yum -y install ttmkfdir \
	&& ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir \
	&& cp /var/tmp/simsun.ttc /usr/share/fonts/dejavu \
	&& fc-cache 

问题解决效果:

Docker 内JAVA用SVG代码转PNG , 图片中文乱码问题_第2张图片

你可能感兴趣的:(采坑记,JAVA开发)