Sunday 15 March 2015

Capturing Screenshots from the Command Line using Java

A few weeks ago I spent most of a day trying to work out how to capture a screen shot from the command line on Windows.  MS don't provide anything to do this.  You can manually [Prtscr], open Paint, Ctrl-V, Save As, but you can't automate it.  And you can't seem to automate the SnippingTool - or even run it from a script.  There are tools you can download from dodgy websites, but I don't want to do that.

It was a bit annoying to realize that I should have started with Java.  The follow captures all attached screens with JDK 1.7:
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Snapshot {

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        int screenNumber = 1;
        for(GraphicsDevice gd : ge.getScreenDevices()){
            DisplayMode dm = gd.getDisplayMode();
            Rectangle rect = new Rectangle(dm.getWidth(),
                                              dm.getHeight());

            BufferedImage image = robot.createScreenCapture(rect);
            File f = new File("screen" + screenNumber + ".png");
            ImageIO.write(image, "PNG", f);
        }
    }
}

No comments:

Post a Comment