Start Search Contents Index Links About

Save that screen

Simple screencapture and image output

2007 - Week 11 - Havard Rast Blok

Caputring the screen is easy in Java, using the java.awt.Robot class. Saving is also a breeze, with the javax.imageio package. Binding it all together, is the java.awt.image.BufferedImage class.

Capturing the screen is just a one-liner in Java, using the java.awt.Robot class. Its createScreenCapture(Rectangle) method takes the location and size of the area to capture in screen pixel cooridnates. Getting the size of the current screen device is covered in another article, so let's just assume we have a method which returns this as a Rectangle.

Robot robot = new Robot();
Rectangle screenSize = getScreenSize();
BufferdImage screen = robot.createScreenCapture(screenSize);

Once the screen is stored as a java.awt.image.BufferedImage, it can easily be written to file using the classes from the javax.imageio package. It supports reading and writing of the most common image formats, including JPEG, PNG, BMP and reading of GIF.

//set the image file format to use for frame saving
Iterator ite = ImageIO.getImageWritersByFormatName("png");
ImageWriter imgWriter = (ImageWriter) ite.next();

//create a output streams
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(fileName));
ImageOutputStream ios = ImageIO.createImageOutputStream(bout);

//assign it to the image writer, and write the image 
imgWriter.setOutput(ios);
imgWriter.write(screen);

//always remember to close any streams and writers used 
ios.close();
bout.close();

Here's sample application which uses the methods mentioned above, for now, the output is hardcoded to save the full screen to test.png, which of course can be easily changed.


ScreenCapture.java



site: Håvard Rast Blok
mail:
updated: 27 July 2007