Is there a way to take a screenshot using Java and save it to some sort of image?

后端 未结 8 818
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:19

Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then gra

8条回答
  •  独厮守ぢ
    2020-11-22 07:00

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();  
    GraphicsDevice[] screens = ge.getScreenDevices();       
    Rectangle allScreenBounds = new Rectangle();  
    for (GraphicsDevice screen : screens) {  
           Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();        
           allScreenBounds.width += screenBounds.width;  
           allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
           allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
           allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
          } 
    Robot robot = new Robot();
    BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
    File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
    if(!file.exists())
        file.createNewFile();
    FileOutputStream fos = new FileOutputStream(file);
    ImageIO.write( bufferedImage, "png", fos );
    

    bufferedImage will contain a full screenshot, this was tested with three monitors

提交回复
热议问题