有没有办法使用Java截取屏幕截图并将其保存为某种图像?

问题

标题简单说明:你是否只能使用Java命令截取屏幕并保存?或者,我是否需要使用特定于操作系统的程序来截取屏幕截图然后将其从剪贴板中取出?


#1 热门回答(167 赞)

信不信由你,你实际上可以使用java.awt.Robot"创建一个包含从屏幕读取像素的图像"。然后,你可以将该映像写入磁盘上的文件。

我刚试了一下,整个事情最终结果如下:

Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));

注意:这只会捕获主监视器。有关多显示器支持,请参见GraphicsConfiguration


#2 热门回答(20 赞)

我从不喜欢使用Robot,所以我制作了自己的简单方法来制作JFrame对象的截图:

public static final void makeScreenshot(JFrame argFrame) {
    Rectangle rec = argFrame.getBounds();
    BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
    argFrame.paint(bufferedImage.getGraphics());

    try {
        // Create temp file
        File temp = File.createTempFile("screenshot", ".png");

        // Use the ImageIO API to write the bufferedImage to a temporary file
        ImageIO.write(bufferedImage, "png", temp);

        // Delete temp file when program exits
        temp.deleteOnExit();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

#3 热门回答(16 赞)

如果你想捕获所有监视器,可以使用以下代码:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();

Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
    Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();

    allScreenBounds.width += screenBounds.width;
    allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}

Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);