In this example you’ll see how to create a screen capture / screenshot and save it as an image file such a PNG image. Some classes are use in this program including the java.awt.Robot
, java.awt.image.BufferedImage
and javax.imageio.ImageIO
.
package org.kodejava.awt;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.io.File;
import java.io.IOException;
public class ScreenCapture {
public static void main(String[] args) {
try {
Robot robot = new Robot();
// Capture screen from the top left in 200 by 200 pixel size.
BufferedImage bufferedImage = robot.createScreenCapture(
new Rectangle(new Dimension(200, 200)));
// The captured image will the written into a file called
// screenshot.png
File imageFile = new File("screenshot.png");
ImageIO.write(bufferedImage, "png", imageFile);
} catch (AWTException | IOException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024