Thursday, April 12, 2012

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 http://codereview.stackexchange.com/questions/10783/java-screengrab



Answer:

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

No comments:

Post a Comment