Screen Capture in Java not capturing whole screen
Asked Answered
P

2

4

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

Profusive answered 6/4, 2012 at 10:13 Comment(0)
V
10

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);
 ...
Volkman answered 6/4, 2012 at 10:31 Comment(0)
A
0

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);;
    }
}
Amboceptor answered 6/2, 2017 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.