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


问题发生

我之前在使用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: 无法打开共享对象文件: 没有那个文件或目录
20200331171418

2.Could not initialize class java.awt.image.BufferedImage
20200331171456


问题代码如下:

其实也就是网上随便找的一份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"

20200402104824

补充:

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

posted @ 2020-04-02 10:55  随风行云  阅读(979)  评论(0编辑  收藏  举报