0

I am working on Java project. I need to capture screens shots of different operating systems.

String outFileName = "c:\\Windows\\Temp\\screen.jpg";
 try{
    long time = Long.parseLong(secs) * 1000L;
    System.out.println("Waiting " + (time / 1000L) + " second(s)...");
    //Thread.sleep(time);
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    Rectangle screenRect = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRect);
    ImageIO.write(image, "jpg", new File(outFileName));
  }catch(Exception screen){}

Using the above code it is capturing the screen shots from Windows XP but it is not capturing in other operating systems. Is there any other method I need to keep to make it work in all operating systems?

user1448108
  • 467
  • 2
  • 10
  • 28
  • 2
    Please explain _"not capturing in other operating systems"_. Exception? Empty output file? Something else? You're ignoring all exceptions, which means you may not be seeing the cause of failure. At least print the stack trace in the `catch` block. – Jim Garrison Oct 25 '12 at 06:47
  • 4
    First of all: **never** ignore exceptions with an empty catch block like this. *At least* use `e.printStackTrace()` (oh, and don't call your exception variable `screen`, that's just confusing). – Joachim Sauer Oct 25 '12 at 06:47
  • 1
    @JoachimSauer or just throw up[wards]. The runtime environment will display the error for you. – John Dvorak Oct 25 '12 at 06:50
  • 1
    Also: that path is *probably* not valid on most non-Windows OS. – Joachim Sauer Oct 25 '12 at 06:51

1 Answers1

2

This is a very watered down version of some of the code we use...

try {

    Robot robot = new Robot();

    GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    Area area = new Area();
    for (GraphicsDevice gd : screenDevices) {
        area.add(new Area(gd.getDefaultConfiguration().getBounds()));
    }

    Rectangle bounds = area.getBounds();
    System.out.println(bounds);
    BufferedImage img = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();
    for (GraphicsDevice gd : screenDevices) {
        Rectangle screenBounds = gd.getDefaultConfiguration().getBounds();
        BufferedImage screenCapture = robot.createScreenCapture(screenBounds);
        g2d.drawImage(screenCapture, screenBounds.x, screenBounds.y, null);
    }

    g2d.dispose();
    ImageIO.write(img, "png", new File("path/to/ScreenShot.png"));

} catch (Exception exp) {
    exp.printStackTrace();
}

This works on Windows 7 and XP. I'll test my Mac when I get home

UPDATED

I've being able to verify Mac OS 10.7.5 using JDK 7 and JDK 6

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366