Flying Saucer exception in headless environment

Flying saucer is a good project to convert html page to image, the code is rather simple:

BufferedImage buff = Graphics2DRenderer.renderToImage("http://www.w3c.org",  800, 600);

This code will convert w3c.org page to an image file.

This library is run perfectly in a normal computer, but if you want to deploy to a server, with no X11 interface, you will get this exception:

java.lang.ClassCastException: sun.java2d.HeadlessGraphicsEnvironment cannot be cast to sun.java2d.SunGraphicsEnvironment

or

java.awt.HeadlessExceptionNo X11 DISPLAY variable was set

Because java.awt need a GUI to process, if the X11 is not presented, usually because is run on terminal, this exception will be thrown. After I check the Graphics2DRenderer source file, the comment actually indicate headless environment is supported.

The “bug” actually come from another class – ImageUtil, somehow it doesn’t check for headless and straightaway “getGraphicsConfiguration”, so we need to fix it. Need to comment the original code of makeCompatible, and apply the code below:

public static BufferedImage makeCompatible(BufferedImage bimg) {
 BufferedImage cimg = createCompatibleBufferedImage(bimg.getWidth(), bimg.getHeight(), bimg.getTransparency());
 Graphics cg = cimg.getGraphics();
 cg.drawImage(bimg, 0, 0, null);
 cg.dispose();
 return cimg;
 }

the exact code can found at here, you need to recompile the library.



Leave a Comment