Taking Screenshots using JAVA

programming

Screenshots are often required while working with projects. There are many solutions available, like the inbuilt Snipping Tool (Windows). But I wanted to have an integrated solution to my Desktop application which I run whenever my pc runs and interacts with my home automation system for tasks like device control to email notifications and so on. As my application is written in JAVA, I searched for the same. So here is how I am taking Desktop screenshots using JAVA.

The way it works is, it opens up a transparent JFrame (Fullscreen), on top of that you can draw a rectangle, and when the Take Snap button is clicked, the are covered under the rectangle is saved as an image.

The piece of code that takes the snap is ,

private final static void takeSnap() {
    try {
        Robot robot = new Robot();
        Rectangle area = new Rectangle(jt.getBounds());
        BufferedImage bufferedImage = robot.createScreenCapture(area);
        File file = new File(path+"\\screenshot_"+sdf.format(new Date())+".png");
        boolean i = ImageIO.write(bufferedImage, "jpg", file);
        if (i) {
            JOptionPane.showMessageDialog(frame2, "Snapshot Taken Sucessfully !!");
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(frame2, "Error Taking Snapshot !!");
        e.printStackTrace();
    }
}

Here I have used the Robot class to take the screen capture. Which a method createScreenCapture (Creates an image containing pixels read from the screen. This image does not include the mouse cursor.)

If you are using the program, make sure to change the drive path otherwise it will throw an error.

The complete code is as follows,

 

Related posts

Leave a Comment