我正在研究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捕获屏幕截图,但它不能在其他操作系统中捕获。我还需要保留其他方法才能使其在所有操作系统中都能正常运行吗?
答案 0 :(得分: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