KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test > Screenshot


1 package test;
2
3 /*
4  * Screenshot.java (requires Java 1.4+)
5  */

6
7 import java.awt.Dimension JavaDoc;
8 import java.awt.Rectangle JavaDoc;
9 import java.awt.Robot JavaDoc;
10 import java.awt.Toolkit JavaDoc;
11 import java.awt.image.BufferedImage JavaDoc;
12 import java.io.File JavaDoc;
13
14 import javax.imageio.ImageIO JavaDoc;
15
16 public class Screenshot
17 {
18
19     public static void main(String JavaDoc[] args) throws Exception JavaDoc
20     {
21         // make sure we have exactly two arguments,
22
// a waiting period and a file name
23
if (args.length != 2)
24         {
25             System.err.println("Usage: java Screenshot "
26                     + "WAITSECONDS OUTFILE.png");
27             System.exit(1);
28         }
29         // check if file name is valid
30
String JavaDoc outFileName = args[1];
31         if (!outFileName.toLowerCase().endsWith(".png"))
32         {
33             System.err.println("Error: output file name must "
34                     + "end with \".png\".");
35             System.exit(1);
36         }
37         // wait for a user-specified time
38
try
39         {
40             long time = Long.parseLong(args[0]) * 1000L;
41             System.out.println("Waiting " + (time / 1000L) + " second(s)...");
42             Thread.sleep(time);
43         }
44         catch (NumberFormatException JavaDoc nfe)
45         {
46             System.err.println(args[0] + " does not seem to be a "
47                     + "valid number of seconds.");
48             System.exit(1);
49         }
50         // determine current screen size
51
Toolkit JavaDoc toolkit = Toolkit.getDefaultToolkit();
52         Dimension JavaDoc screenSize = toolkit.getScreenSize();
53         Rectangle JavaDoc screenRect = new Rectangle JavaDoc(screenSize);
54         // create screen shot
55
Robot JavaDoc robot = new Robot JavaDoc();
56         BufferedImage JavaDoc image = robot.createScreenCapture(screenRect);
57         // save captured image to PNG file
58
ImageIO.write(image, "png", new File JavaDoc(outFileName));
59         // give feedback
60
System.out.println("Saved screen shot (" + image.getWidth() + " x "
61                 + image.getHeight() + " pixels) to file \"" + outFileName
62                 + "\".");
63         // use System.exit if the program hangs after writing the file;
64
// that's an old bug which got fixed only recently
65
// System.exit(0);
66
}
67 }
Popular Tags