Saturday, September 20, 2003

J2SE: Taking screen snapshots in JAVA

As programmers many a times we need take snap shots of our screens. If we can take snap shot in java why use OS specific way to take a snap shot?
Here is a simple code example of taking snapshot in java (Either PNG format or JPEG format):




01 import java.awt.AWTException;
02 import java.awt.Dimension;
03 import java.awt.Rectangle;
04 import java.awt.Robot;
05 import java.awt.Toolkit;
06 import java.awt.image.RenderedImage;
07 import java.io.File;
08 import java.io.IOException;
09 import javax.imageio.ImageIO;
10 
11 /**
12  * A Simple program that saves current screen snapshot.
13  * Supported formats png and jpg.
14  * Usage java ScreenSnapShot <<outputfilename>>
15  *
16  @author Kumar Mettu
17  @version 0.61
18  */
19 public class ScreenSnapShot {
20 
21     public static void main(String[] argsthrows IOException,AWTException {
22 
23         String saveFileName = "default.png";
24         String saveFileFormat = "png";
25 
26         if (args.length > 0)
27             saveFileName = args[0];
28 
29         if (saveFileName.toLowerCase().endsWith(".png")) {
30             saveFileFormat = "png";
31         else if (saveFileName.toLowerCase().endsWith(".jpg"||
32                    saveFileName.toLowerCase().endsWith(".jpeg")) {
33             saveFileFormat = "jpg";
34         else {
35             System.err.println("Only png and jpg formats are supported.");
36             System.exit(1);
37         }
38 
39         // get current sceen size for snapshot.
40         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
41         Rectangle screenRect = new Rectangle(screenSize);
42 
43         // create current screen snapshot
44         RenderedImage image = (new Robot()).createScreenCapture(screenRect);
45 
46         if (ImageIO.write(image, saveFileFormat, new File(saveFileName))) {
47             System.out.println("Screen snap shot is saved as :" + saveFileName);
48         else {
49             System.out.println("Unable to save snap shot");
50         }
51     }
52 }



This code requires J2SE1.4. There is no real use of this code unless you extend it to make use of it(like taking snapshots at fixed intervals etc...).

2 comments:

Anonymous said...

ThankZ !

Anonymous said...

simple and elegant.