Donnerstag, 18. Juni 2009

Create an image of an invisible Swing component

Yesterday we have tried to write an image of an invisible, better say, a component that has not yet been added to an already visible component on the screen. In other words, we have created an instance of a JPanel, added different stuff to it and wanted to create an PNG image out of it, without added the panel to the main application window. After several trials we have finally asked Google and found a nice solution (link):

public static BufferedImage
createImage(JComponent component, int imageType) {
Dimension componentSize = component.getPreferredSize();
component.setDoubleBuffered(false);
component.setSize(componentSize);
component.addNotify();
component.validate();

BufferedImage img = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(component.getSize().width,
component.getSize().height);
Graphics2D grap = img.createGraphics();
grap.setColor(Color.WHITE);
grap.fillRect(0, 0, img.getWidth(), img.getHeight());
component.print(grap);
grap.dispose();
return img;
}


You can now call this method like this:

BufferedImage image = createImage(p, BufferedImage.TYPE_INT_RGB);
ImageIO.write(image, "png", new File("/Users/giemza/Component.png"));


One thing that we have found out is that if you are working on a remote X11 connection the compatible image is a X11RemoteOffScreenImage. If you try to write this image with ImageIO under Java 1.5.0, the application will crash without any exceptions. Just no reaction. We could not reproduce this behaviour with Java 1.6.0.

Keine Kommentare: