简体   繁体   中英

Is there a way to headlessly screenshot a swing (or awt) window?

There is a legacy app that uses swing, and it spawns various windows for various purposes at various times. What I'm wondering is if it possible to get a "screenshot" of each window, without having to actually go through the screenshot utility on my OS. I know this is possible somehow, but I'm wondering if it is something nicely supported by swing/java? I'd love to just load a file via this app, iterate over the windows spawned, and write an image out somewhere.

There's two ways I know to do this, one if you want to capture the window's decorations (the buttons at the top, and other similar contents), and one if you don't.

If you don't want to capture the decorations, you can simply paint it to an image, like this:

public static void saveImage(JFrame frame, File target, String extension) throws IOException{
    BufferedImage img = new BufferedImage(frame.getContentPane().getWidth(),
                                          frame.getContentPane().getHeight(),
                                          BufferedImage.TYPE_INT_RGB);
    frame.getContentPane().paint(img.getGraphics());
    ImageIO.write(img, extension, target);
}

This creates a new image of the required size, draws your contents into it, and then saves it.

If you want to capture everything, you can use the Robot class's createScreenCapture method , like this:

public static void saveImage(JFrame frame, File target, String extension) throws IOException{
    Point pos = frame.getLocationOnScreen();
    Dimension size = frame.getSize();
    Rectangle rect = new Rectangle(pos.x, pos.y, size.width, size.height);
    Robot robot = new Robot();
    BufferedImage bi = robot.createScreenCapture(rect);
    ImageIO.write(bi, extension, target);
}

As for getting each window to screenshot, you can either manually track the ones you want, or use Frame.getFrames() or Window.getWindows() to get an array of all active ones, and then iterate over them.

Sikuli is pretty neat, it allows you to automate anything, based on image recognition. Their site: www.sikuli.org . And it can take screenshot while running the automated task you scripted: How to take screenshot with sikuli

I'm not affiliate to sikuli whatsoever, I simply used it in the past (to automate tests on a swing GUI). The description on their site:

Sikuli automates anything you see on the screen. It uses image recognition to identify and control GUI components. It is useful when there is no easy access to a GUI's internal or source code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM