Java screen capture example code 

Joined:
03/07/2011
Posts:
57

April 08, 2011 11:05:24    Last update: April 08, 2011 11:05:24
Key points:
  • Use java.awt.Robot to capture a screen region as java.awt.image.BufferedImage.
  • Use javax.imageio.ImageIO to write image out to a file.


import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ScreenCapture {
    public static void main(String args[]) 
	throws AWTException, IOException {

	// Capture whole screen as JPG
	capture(
	    new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()),
	    "jpg",
	    new File("screenCapture.jpg")
	);

	// Capture whole screen as PNG
	capture(
	    new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()),
	    "png",
	    new File("screenCapture.png")
	);
    }

    public static void capture(Rectangle area, 
			       String formatName, 
			       File outputFile) 
	throws AWTException, IOException {
	BufferedImage screenArea = new Robot().createScreenCapture(area);
	ImageIO.write(screenArea, formatName, outputFile);
    }
}
Share |
| Comment  | Tags