devxlogo

Using the createScreenCapture Method to Capture Your Screen

Using the createScreenCapture Method to Capture Your Screen

The Robot class in Java provides a special method to capture your screen. This method creates an image containing pixels read from the screen and returns a BufferedImage class object. Here is an example to capture your screen. The image will be saved into a JPEG file.

 /* * @(#)ScreenCapture.java 2001/09/24 * * Usage: java ScreenCapture [-d seconds] [-f filename] * * @Author *	Cheng-Yu Chang  * * @License * 	GPL(GNU GENERAL PUBLIC LICENSE) *	http://www.gnu.org/copyleft/gpl.html */import java.awt.*;import java.awt.image.*;import java.io.*;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;public class ScreenCapture  	public static void ScreenCapture(int seconds, _String filename) {  		Robot robot = null;   		// remember to catch AWTException   		try {      			robot =new Robot();      			// delay the time			robot.delay(seconds);			// encode to jpg file            		OutputStream f = new _FileOutputStream(filename);            		JPEGImageEncoder encoder = _JPEGCodec.createJPEGEncoder(f);            		encoder.encode(robot.createScreenCapture(newRectangle(Toolkit.getDefaultToolkit().getScreenSize())));            		f.close();     		}     		catch(AWTException e1) {}     		catch(IOException e2) {}  	}  	// Usage  	private static void usage() {  		System.out.println("Usage: _java ScreenCapture [-d seconds] [-ffilename]");  		System.out.println("	-d Seconds to _delay before capturing screen");  		System.out.println("	-f JPG filename to save");  		System.exit(0);  	} 	public static void main(String args[]) { 		int s = 0; 		String filename = "ScreenCapture.jpg"; 		// determine the arguments 		if (args.length == 0)	  		usage();	  	else {	  		for (int i = 0 ; i < _args.length ; i++) {	  			if _(args[i].startsWith("-")) {	  				if _(args[i].equals("-d")) {	  					if _(i < args.length - 1)	  						_s = Integer.parseInt(args[++i]);	  					else	  						_usage();	  				}	  				_if (args[i].equals("-f")) {	  					_if (i < args.length - 1)	  						_filename = args[++i];	  					else	  						_usage();	  				}	  			}	  			else	  				usage();	  		}	  	}  		ScreenCapture(s * 1000, filename);  		System.exit(0); 	}}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist