Java Program to capture window screen-shot.
Objective
Write a Java program to capture a screenshot of the computer screen and save it as an image.
Algorithm / Approach
- Import
java.awt.Robotandjavax.imageio.ImageIO. - Instantiate the
Robotclass. - Create a
Rectangleobject defining the screen dimensions to capture. - Call
robot.createScreenCapture(scr)to take the snapshot and store it in aBufferedImage. - Use
ImageIO.write()to save the image to the hard drive as a JPG file.
ScreenShot.java
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
class ScreenShot {
public static void main(String[] args)
throws Exception {
Robot robot = new Robot();
String ext = "jpg";
String fileName = "ProwessCapture."+ext;
Rectangle scr=new Rectangle(1250,800);
BufferedImage img;
img = robot.createScreenCapture(scr);
ImageIO.write(img,ext,new File(fileName));
System.out.println("A screenshot saved!");
}
}
Expected Output
A screenshot saved! //image will save in current directory //with name ProwessCapture.jpg
Explanation of the Program
- The
Robotclass is a powerful tool in Java AWT used to generate native system input events (simulating mouse clicks, keyboard presses, etc.) and reading the screen. - It is primarily used for automated GUI testing, but its
createScreenCapturemethod makes it extremely easy to build a custom snipping tool or screen recording software in Java.
Complexity
Time Complexity
O(1)
Space Complexity
O(n) - Based on the image resolution.