Share this page 

Get a screen capture and save it as a JPEGTag(s): AWT


The screen capture is done with java.awt.Robot.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

class ScreenCapture {
  public static void main(String args[]) throws
           AWTException, IOException {
     // capture the whole screen
     BufferedImage screencapture = new Robot().createScreenCapture(
           new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );

     // Save as JPEG
     File file = new File("screencapture.jpg");
     ImageIO.write(screencapture, "jpg", file);

     // Save as PNG
     // File file = new File("screencapture.png");
     // ImageIO.write(screencapture, "png", file);
  }
}

To capture a specific area

BufferedImage screencapture = new Robot().createScreenCapture(
   new Rectangle( 15, 15, 150, 150));

To capture a specific visual object

BufferedImage image = new Robot().createScreenCapture( 
   new Rectangle( myframe.getX(), myframe.getY(), 
                  myframe.getWidth(), myframe.getHeight() ) );