awt

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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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

I have read and agree to the terms & conditions

 

Ilias Tsagklis

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
naveen
naveen
5 years ago

iam getting black screen

Back to top button