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.

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
6 years ago

iam getting black screen

Back to top button