2012-10-25 107 views
0

我正在從事Java項目。我需要捕獲不同操作系統的屏幕截圖。如何在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的屏幕截圖,但它不捕獲其他操作系統。有沒有其他方法可以讓我們在所有操作系統中都能正常工作?

+2

請解釋_「不是在其他拍攝驗證的Mac OS 10.7.5操作系統」_。例外?空輸出文件?還有別的嗎?你忽略了所有的例外,這意味着你可能沒有看到失敗的原因。至少在「catch」塊中打印堆棧跟蹤。 –

+4

首先:**從不**用這樣的空catch塊來忽略異常。 *至少*使用'e.printStackTrace()'(哦,並且不要調用你的異常變量'screen',這只是令人困惑)。 –

+1

@JoachimSauer或只是吐出[病房]。運行時環境將爲您顯示錯誤。 –

回答

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

相關問題