Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 8, 2002

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 <ccy0927@ms16.hinet.net>
 *
 * @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(new
Rectangle(Toolkit.getDefaultToolkit().getScreenSize())));
            		f.close();
     		}
     		catch(AWTException e1) {}
     		catch(IOException e2) {}

  	}

  	// Usage
  	private static void usage() {
  		System.out.println("Usage: _
java ScreenCapture [-d seconds] [-f
filename]");
  		System.out.println("\t-d Seconds to _
delay before capturing screen");
  		System.out.println("\t-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);
 	}

}
Cheng-Yu Chang
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date