How to save as image an on-screen Canvas3D?

634 views Asked by At

I'm doing a program to create a die (cube) with different image textures based on the input of the user (user choose images on a SWT GUI).

Once the user choose the images, it can visualize the dice on a separate dialog, and perform some rotate operations over it (see, after perform a small rotation to see three faces in the screenshots).

See screenshots: http://pastebin.com/XqJfXL6i

And my problem starts here: I want to save the content of the canvas (the dice with the background in its current form, after being rotated). I've been searching for several codes and I think that my problem is because my current canvas is an "on-screen" canvas and I need an off-screen canvas, which will allow to save the content.

My current code is the following:

http://pastebin.com/ZAv0ATJN

And.. here starts the problem. It throws this exception:

java.lang.IllegalStateException: Canvas3D: Not in off-screen mode

Concretely it fails in this line:

        ImageComponent2D ic2d = canvas.getOffScreenBuffer();

As you can see there are several lines commented that I tried before, but they didn't work neither.

Any clue about how to do it?

Thanks!

1

There are 1 answers

0
alejandrorg On BEST ANSWER

Based on the comment provided by gouessej (thanks!) finally I use this code, which works fine for my doubt:

private void saveImage(String img) throws Exception {
    FileOutputStream fileOut = new FileOutputStream(img);
    Robot r = new Robot();
    BufferedImage bi = r.createScreenCapture(new java.awt.Rectangle(
            (int) frame.getLocationOnScreen().getX(), (int) frame
                    .getLocationOnScreen().getY(), frame.getBounds().width,
            frame.getBounds().height));
    ImageIO.write(bi, "jpeg", fileOut);
    fileOut.flush();
    fileOut.close();
}