Have you ever wanted to grab a screenshot from your Java application? Here's a quick 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(); |
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.*; Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(rectangle); 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());
} |
Although this is a simple example of capturing an entire screen, there are a lot of creative uses for using a screenshot. Some possible uses include:
- Mixing heavy and light weight controls
- Creating special effects such as drop shadows or transparent windows.
- Drawing on the screen directly
discuss this topic to forum
