How do I create a screen capture using Robot class?
Category: java.awt, viewed: 6359 time(s).
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.example.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 writen into a file called
// screenshot.png
//
File imageFile = new File("screenshot.png");
ImageIO.write(bufferedImage, "png", imageFile);
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
More examples on java.awt