Taking Screenshots in Java

Have you ever wanted to grab a screenshot from your Java application? Here's a quick Java tutorial on how to grab a screenshot and save it to a JPEG and PNG file. This shows how to use the Robot class to capture the screen image and the ImageIO API to save it as a JPG and PNG.

First, we need to determine the size of the screen and create a rectangle with the screen dimensions. We can query the toolkit to determine the size of the screen. In our example, we are grabbing the entire screen. You can also use this same method to grab the contents of a window or a specific screen rectangle.

//Get the screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle rect = new Rectangle(0, 0, screenSize.width, screenSize.height);

Next, you will need to create an instance of the Robot and capture the desired rectangle of the screen. The createScreenCapture() method takes a Rectangle and returns a BufferedImage.
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(rectangle);


Finally, we are going to save the screenshot as a PNG and JPG. For this, we will use the ImageIO API to convert from a BufferedImage to a PNG and to a JPG.

//Save the screenshot as a png
file = new File("screen.png");
ImageIO.write(image, "png", file);

//Save the screenshot as a jpg
file = new File("screen.jpg");
ImageIO.write(image, "jpg", file);
The complete screenshot example is below:

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;

...

try
{
//Get the screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle rect = new Rectangle(0, 0,
screenSize.width,
screenSize.height);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(rect);
File file;

//Save the screenshot as a png
file = new File("screen.png");
ImageIO.write(image, "png", file);

//Save the screenshot as a jpg
file = new File("screen.jpg");
ImageIO.write(image, "jpg", file);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}


4 comments:

Anonymous said...

Thanks! That worked just fine.
Cheers
Wolverine

Anonymous said...

Does anyone know how to get a window's content with an Aero desktop layout, just as if it were a normal layout and the window not overlapped by another?

Is that possible with Robot or in Java at all?

Anonymous said...

thank u very much

Anonymous said...

Hey this robot is not able to take the screenshot of when the computer is locked.Do u have any alternative way.

Post a Comment