Home » Desktop Java » awt » Screen capture example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Screen capture example

In this example we are going to see how to take screen captures in a Java Desktop Application.

Basically, all you have to do to take screen captures is:

  • Create a new Robot instance.
  • Create a new Rectangle shape.
  • Use robot.createScreenCapture to get a rectangle screen capture.
  • Use ImageIO to save the image in a file.

 

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CaptureScreen {

  public static void main(String[] args) {

try {

    Robot robot = new Robot();

    // Capture a particular area on the screen

    int x = 50;

    int y = 50;

    int width = 250;

    int height = 250;

    Rectangle area = new Rectangle(x, y, width, height);

    BufferedImage bufferedImage = robot.createScreenCapture(area);

    // Write generated image to a file

    try {

  // Save as PNG

  File file = new File("screenshot_small.png");

  ImageIO.write(bufferedImage, "png", file);

    } catch (IOException e) {

  System.out.println("Could not save small screenshot " + e.getMessage());

    }

    // Capture the whole screen

    area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

    bufferedImage = robot.createScreenCapture(area);

    // Write generated image to a file

    try {

  // Save as PNG

  File file = new File("screenshot_full.png");

  ImageIO.write(bufferedImage, "png", file);

    } catch (IOException e) {

  System.out.println("Could not save full screenshot " + e.getMessage());

    }

} catch (AWTException e) {

  System.out.println("Could not capture screen " + e.getMessage());

}

  }
}

 
This was an example on how to take screen captures in Java.

(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
naveen Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
naveen
Guest
naveen

iam getting black screen