Java中的屏幕捕获无法捕获整个屏幕

时间:2012-04-06 10:13:10

标签: java macos screen awt awtrobot

我有一小段代码用于跟踪时间 - 很简单,它每隔四分钟拍摄一次我的桌面照片,以便稍后我可以回过头来看看我做过的事情。一天 - 它工作得很好,除非我连接到外部显示器 - 这个代码只需要我的笔记本电脑屏幕的屏幕截图,而不是我工作的更大的外部显示器 - 任何想法如何更改代码?我正在运行OSX,以防相关......

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

class ScreenCapture {
    public static void main(String args[]) throws
        AWTException, IOException {
            // capture the whole screen
int i=1000;
            while(true){
i++; 
                BufferedImage screencapture = new Robot().createScreenCapture(
                        new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );

                // Save as JPEG
                File file = new File("screencapture"+i+".jpg");
                ImageIO.write(screencapture, "jpg", file);
try{
Thread.sleep(60*4*1000);
}
catch(Exception e){
e.printStackTrace();
}

            }
        }
}

根据给出的解决方案,我做了一些改进,感兴趣的代码正在https://codereview.stackexchange.com/questions/10783/java-screengrab进行代码审查

2 个答案:

答案 0 :(得分:10)

有一个教程Java multi-monitor screenshots,展示了如何做到这一点。 基本上你必须迭代所有屏幕:

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

for (GraphicsDevice screen : screens) {
 Robot robotForScreen = new Robot(screen);
 ...

答案 1 :(得分:0)

我知道这是一个老问题,但是在接受的答案上链接的解决方案可能不适用于某些多显示器设置(在Windows上肯定)。

如果您以这种方式设置显示器,例如: [3] [1] [2]

这是正确的代码:

public class ScreenshotUtil {

    static public BufferedImage allMonitors() throws AWTException {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] screens = ge.getScreenDevices();
        Rectangle allScreenBounds = new Rectangle();
        for (GraphicsDevice screen : screens) {
            Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
            allScreenBounds = allScreenBounds.union(screenBounds);
        }
        Robot robot = new Robot();
        return robot.createScreenCapture(allScreenBounds);;
    }
}