libXrender.so找不到、Couldnot initialize...BufferedImage问题

2022-10-08,,

目录


问题发生

我之前在使用zxing生成二维码的时候,ubuntu上的tomcat报了以下两种错:这两种错有时候不是同时报的,但基本都有关键字眼awt

对于问题发生的原因,我没有进行详细的代码分析。据说是因为我的服务器没有安装视窗界面,导致缺少一部分awt的共享库。而二维码的生成需要使用到awt这个库的bufferedimage,所以就导致提示缺少文件,.so是一种共享库文件。

1.java.lang.unsatisfiedlinkerror: /usr/local/jdk1.8/jre/lib/amd64/libawt_xawt.so: libxrender.so.1: 无法打开共享对象文件: 没有那个文件或目录

2.could not initialize class java.awt.image.bufferedimage


问题代码如下:

其实也就是网上随便找的一份zxing生成二维码的代码:

public class qrcodergenerator {

    public static string getencode(string content) throws exception {


        int width = 128; // 图像宽度
        int height = 128; // 图像高度
        string format = "png";// 图像类型
        map<encodehinttype, object> hints = new hashmap<encodehinttype, object>();
        hints.put(encodehinttype.character_set, "utf-8");
        hints.put(encodehinttype.margin, 3);

        bitmatrix bitmatrix = new multiformatwriter().encode(content,
                barcodeformat.qr_code, width, height, hints);// 生成矩阵
        bytearrayoutputstream outputstream = new bytearrayoutputstream();
        matrixtoimagewriter.writetostream(bitmatrix, format, outputstream);// 输出图像
        base64.encoder encoder = base64.getencoder();

        string text = encoder.encodetostring(outputstream.tobytearray());

        ioutils.closequietly(outputstream);

        return text;
    }
}


问题的解决

  • 优先选择的方法:通过在代码层次设置headless
public class qrcodergenerator {

    public static string getencode(string content) throws exception {

        // 加入下面一行代码即可
        system.setproperty("java.awt.headless","true");

        int width = 128; // 图像宽度
        int height = 128; // 图像高度
        string format = "png";// 图像类型
        map<encodehinttype, object> hints = new hashmap<encodehinttype, object>();
        hints.put(encodehinttype.character_set, "utf-8");
        hints.put(encodehinttype.margin, 3);

        bitmatrix bitmatrix = new multiformatwriter().encode(content,
                barcodeformat.qr_code, width, height, hints);// 生成矩阵
        bytearrayoutputstream outputstream = new bytearrayoutputstream();
        matrixtoimagewriter.writetostream(bitmatrix, format, outputstream);// 输出图像
        base64.encoder encoder = base64.getencoder();

        string text = encoder.encodetostring(outputstream.tobytearray());

        ioutils.closequietly(outputstream);

        return text;
    }
}
  • 通过启动项来设置headless:
    修改/bin/catalina.sh,在$java_opts加入:
      -djava.awt.headless=true \

可以在文件的最后一行加上这个,或者找一个没有if包括的行加上:
java_opts="$java_opts -djava.awt.headless=true"

补充:

  • headless是一种工作模式,可以解决上面的服务端没有gui界面的尴尬,此时会要求程序依赖软件层次来模拟出这样的功能,当然了,并不是真的模拟出来,就是模拟出有这个东西的时候应该提供的数据。随便搜了一下,好像比较热门的是headless chrome,据说是不需要桌面环境的浏览器。。。

《libXrender.so找不到、Couldnot initialize...BufferedImage问题.doc》

下载本文的Word格式文档,以方便收藏与打印。