Archive for March, 2007

Capture Screenshot in Java

March 2, 2007

I was trying to generate the thumbnail of an HTML page through Java. I could not find a great way, but in the process I found how to capture the screen in a Java program. It is pretty easy. The following program opens the IE in a full screen mode and then captures the screen. This image can be used later on to get the smaller sized image.  

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;

public class ScreenCapture {
  public static void main(String[] args) throws Exception {
  Runtime rt = Runtime.getRuntime();
  String[] cmd = new String[3];
  cmd[0]="C:/Program Files/Internet Explorer/iexplore.exe";
  cmd[1]="-k"; // Open the browser in full screen mode
  Process process = rt.exec(cmd);
  // Sleep for some time so that page can be loaded fully by browser
  Robot robot = new Robot();
  // Capture the screen shot
  BufferedImage bi=robot.createScreenCapture(
  new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
  ImageIO.write(bi, "jpg", new File("C:/imageTest.jpg"));
  // Kill the browser