0

我正在从事 Java 项目。我需要捕获不同操作系统的屏幕截图。

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

使用上面的代码,它正在从 Windows XP 中捕获屏幕截图,但在其他操作系统中没有捕获。我需要保持其他任何方法以使其在所有操作系统中都能正常工作吗?

4

1 回答 1

2

这是我们使用的一些代码的一个非常淡化的版本......

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

这适用于 Windows 7 和 XP。回家后我会测试我的 Mac

更新

我已经能够使用 JDK 7 和 JDK 6 验证 Mac OS 10.7.5

于 2012-10-25T07:21:07.100 回答