Java - how to export a Container to a BufferedImage?

Discussion in 'Mac Programming' started by wrldwzrd89, Mar 29, 2010.

  1. wrldwzrd89 macrumors G5

    wrldwzrd89

    Joined:
    Jun 6, 2003
    Location:
    Solon, OH
    #1
    Is there a way, in Java, to take a given Container, and have it recursively draw the whole layout (including sub-containers, and THEIR sub-containers, etc.) to a BufferedImage object? Among other things, being able to do this would make supporting printing a LOT easier, even if the printing has to be done in an external program, by way of exporting the BufferedImage object to a PNG file then opening it in an image viewer.

    If an example of what I'm trying to export would help at all, I offer the Mazer5D 3.0.0 beta builds' Object Help (which is dynamically generated) as a good example, here. The executable is there, for Mac OS X, Windows, and other platforms, along with the source code.
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    If I understand your question correctly, something like:
    Code:
      yourContainer.paint( yourBufferedImage.createGraphics() );
    
    You might have to futz with the Container's size & location first. Or maybe use a transform on the Graphics2D.
     
  3. wrldwzrd89 thread starter macrumors G5

    wrldwzrd89

    Joined:
    Jun 6, 2003
    Location:
    Solon, OH
    #3
    This is giving me a black image, for some reason... it writes the image okay, but nothing gets displayed when I open it in an image editor.

    Here is the code I'm using, with comments added:
    Code:
    // Temp code to export help
    Container c = this.hv.getHelp(); // Some Container object we're given
    Dimension d = c.getPreferredSize();
    BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
    c.paintAll(bi.createGraphics());
    try {
    	ImageIO.write(bi, "PNG", new File("objecthelp.png"));
    	Messager.showTitledDialog("Exporting help was successful", "Help");
    } catch (IOException io) {
    	Messager.showErrorDialog("Error exporting help!", "Error");
    }
    // End temp code
    
     
  4. wrldwzrd89 thread starter macrumors G5

    wrldwzrd89

    Joined:
    Jun 6, 2003
    Location:
    Solon, OH
    #4
    Success! I finally got this to work properly, by calling paintComponents() instead of paint(), and changing the color of the BufferedImage object to the same as the background color of the help, with a nested for loop. :D
     

Share This Page