Friday, May 20, 2011

How to take a screenshot of your desktop

This tutorial shows you how to capture a screenshot of your desktop.
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

try {
  Robot robot = new Robot();
  //I assume that the size of the image you want is 300 x 200
  BufferedImage img = robot.createScreenCapture(new                                                Rectangle(300,200));
  //I am saving the image as a png image
  //But you can use any other image formats like bmp, jpg etc.
  ImageIO.write(img, "png", new File("D:/screen.png"));
} catch (Exception ex) {
  ex.printStackTrace();
}

Ok. But sometimes you may want to capture the whole screen.
So you have to import Toolkit first.
import java.awt.Toolkit;

Your new code will look like this.
try {
  Robot robot = new Robot();
  Rectangle rect = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize());
  BufferedImage img = robot.createScreenCapture(rect);
  ImageIO.write(img, "png", new File("D:/screen.png"));
} catch (Exception ex) {
  ex.printStackTrace();
}

No comments:

Post a Comment