Java Program to take Screenshots

In this program we will see how we can take screenshots using a java program and save the screenshot in desired folder.
We use java.awt.Robot class to capture pixels of screen. It provides method like createScreenCapture which captures the current screen. This method returns captured image as BufferedImage object which can be saved as a file. It also uses ImageIO to save it as PNG image format. Toolkit.getDefaultToolkit().getSize() method is used to get the size of screen.
The serialVersionUID is universal version identifier for Serializable class. Thread is used so that after executing the program we can switch to the screen we want to take screenshot of. 120s is the time in seconds i.e. 2 mins.

NOTE : Please keep note of UpperCase and LowerCase in name of methods. A slight change of Case may cause errors.

How to use the program to capture Screenshot :

  • Write program in Notepad.
  • Save it as Screenshot.java and run it on CommandPrompt.
  • Refer to the screenshots at end in case of any problem.
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Capture full
// Image of Screen
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.File;
import javax.imageio.ImageIO;
  
public class Screenshot {
    public static final long serialVersionUID = 1L;
    public static void main(String[] args)
    {
        try {
            Thread.sleep(120);
            Robot r = new Robot();
  
            // It saves screenshot to desired path
            String path = "D:// Shot.jpg";
  
            // Used to get ScreenSize and capture image
            Rectangle capture = 
            new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage Image = r.createScreenCapture(capture);
            ImageIO.write(Image, "jpg", new File(path));
            System.out.println("Screenshot saved");
        }
        catch (AWTException | IOException | InterruptedException ex) {
            System.out.println(ex);
        }
    }
}

chevron_right


Output :

References:
http://viralpatel.net/blogs/how-to-take-screen-shots-in-java-taking-screenshots-java/
http://www.javatechblog.com/java/how-to-take-screenshot-programmatically-in-java/



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.