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

后端 未结 8 733
盖世英雄少女心
盖世英雄少女心 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

    I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:

    public static final void makeScreenshot(JFrame argFrame) {
        Rectangle rec = argFrame.getBounds();
        BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
        argFrame.paint(bufferedImage.getGraphics());
    
        try {
            // Create temp file
            File temp = File.createTempFile("screenshot", ".png");
    
            // Use the ImageIO API to write the bufferedImage to a temporary file
            ImageIO.write(bufferedImage, "png", temp);
    
            // Delete temp file when program exits
            temp.deleteOnExit();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    

提交回复
热议问题