Take a Screenshot in Java and save as PNG/JPG
A screenshot, screen capture, screen cap, screen dump, or screengrab is a visual snapshot in time of the monitor, television, or other visual output device in use. In the following tutorial, we demonstrate how to capture a screenshot in Java and save it as a PNG/JPG. The first example show how to capture a fullscreen screen capture. The second example shows how to capture a partial screen dump. These examples only work when you are running a desktop application. You can also capture screenshots of a web page using selenium, which is explained in my other tutorial.
The java.awt.Robot
class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.
Take Fullscreen Screenshot
The Toolkit.getDefaultToolkit().getScreenSize()
gets the dimensions of the screen. We use these dimensions to create a java.awt.Rectangle
instance. We create a new instance of the java.awt.Robot
class and call the createScreenCapture()
method and pass the perviously created rectangle instance as the argument. This creates a BufferedImage
, which we pass as the first argument in the ImageIO.write()
method. The second argument we pass in the file format. In the third and last argument, we pass an FileOutputStream
that’ll write the image to disk.
package com.memorynotfound.awt;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
public class FullScreen {
public static void main(String... args) throws AWTException, IOException {
Rectangle screenRectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage image = new Robot().createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new FileOutputStream("/tmp/full-screen.png"));
}
}
Capture Partial Screenshot
You can also take a partial screenshot. For this you need to know the exact dimensions.
package com.memorynotfound.awt;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
public class PartialScreen {
public static void main(String... args) throws AWTException, IOException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(0, 0, screenSize.width/2, screenSize.height/2);
BufferedImage image = new Robot().createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new FileOutputStream("/tmp/partial-screen.png"));
}
}
References
- Robot#createScreenCapture JavaDoc
- Toolkit#getScreenSize JavaDoc
- ImageIO#write JavaDoc
- Dimension JavaDoc
- Rectangle JavaDoc