Taking a Screenshot in Java

From PeformIQ Upgrade
Jump to navigation Jump to search

Here is how to capture a screenshot and save it as a JPG file using Java. It is done using the ImageIO API for saving the screenshot as the JPG file and using the Robot class to perform the screenshot.

First the screen dimension should be worked out and then create a rectangle with these dimensions. The screen dimansions can be found using the Toolkit class. The following code snippet show how...

// To determine the screen dimensions.

Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);

After getting the screen dimensions, create an instance of the Robot class and copy the rectangle from the screen. The createScreenCapture() method in the Robot class can be used to get the BufferedImage with the rectangular dimension passed as argument to it. The following code snippet demonstrates how this is done...

// Capture the BufferedImage with createScreenCapture() method.

Robot robot = new Robot();

BufferedImage image = robot.createScreenCapture(rectangle);

Creating the JPG file from the BufferedImage is possible using the ImageIO API to convert the BufferedImage to the JPG file. The following code snippet show how...

// Save the BufferedImage to a JPG File.

File file = new File(“screen.jpg”);

ImageIO.write(image, “jpg”, file);