Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to capture window screen-shot.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Import java.awt.Robot and javax.imageio.ImageIO.
  2. Instantiate the Robot class.
  3. Create a Rectangle object defining the screen dimensions to capture.
  4. Call robot.createScreenCapture(scr) to take the snapshot and store it in a BufferedImage.
  5. 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 Robot class 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 createScreenCapture method 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.
ADVERTISEMENT