Screen Capture in Java not capturing whole screen

烈酒焚心 提交于 2019-12-05 01:13:24

问题


I have a small piece of code that I use to keep track of time - very simply it takes a picture of my desktop every four minutes so that later I can go back over what I've been up to during the day - It works great, except when I connect to an external monitor - this code only takes a screen shot of my laptop screen, not the larger external monitor I'm working from - any ideas how to change the code? I'm running OSX in case that's relevant...

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();
}

            }
        }
}

Following the solution given, I made some improvements and the code, for those interested, is under code review at https://codereview.stackexchange.com/questions/10783/java-screengrab


回答1:


There is a tutorial Java multi-monitor screenshots that shows how to do it. Basically you have to iterate all screens:

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

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



回答2:


I know this is an old question, but the solution linked on the accepted answer does not work probably on some multi monitor setups (on windows for sure).

If you have your monitors setup this way for example: [3] [1] [2]

Here is the correct code:

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);;
    }
}


来源:https://stackoverflow.com/questions/10042086/screen-capture-in-java-not-capturing-whole-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!