Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Screen Capture in Java not capturing whole screen

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

like image 200
Joe Avatar asked Dec 27 '22 03:12

Joe


1 Answers

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);
 ...
like image 59
Andrejs Avatar answered Dec 31 '22 14:12

Andrejs