Take a screenshot and save as image in Java

This code example shows how to take a screen capture and save the data to a file as a PNG-image. The code consists of three methods (plus main method), one that gets the screen size, one that captures the actual screenshot, and one that writes the image data to the file.

Getting the screen size

To get the screen size we obtain the local graphics environment by calling the static method getLocalGraphicsEnvironment on the GraphicsEnvironment class. With that we can call the getDefaultScreenDevice which returns an object of type GraphicsDevice with which we can get an instance of the DisplayMode class. The DisplayMode class encapsulates the width and height (and other data) of a graphics device and we need it to be able to know just how big the screenshot should be. If we would like to capture just a part of the screen we could specify any values as width and height to the constructor of the Rectangle class.

Capture the screenshot

To do the actual screen capture work we use the Robot class of the java.awt package. The Robot class has a method called createScreenCapture which takes a Rectangle (the screen size) as parameter. The return value from this method is a BufferedImage which we have declared as an instance variable.

Saving the image

To output the screen shot data to a file, we use an ImageWriter. The ImageWriter instance is obtained by calling the static method getImageWritersByFormatName of the ImageIO class. The input parameter to this method is the file format (in this case png) that we want, and the return value is an iterator containing all currently registered ImageWriters that claim to be able to encode the named format. Since we only need one, we take the first in line (should there be more than one).

The ImageWriter needs an output stream to write the image to and we call the method createImageOutputStream of the ImageIO class to which we send a BufferedOutputStream containing the FileOutputStream that points to the actual file. The actual writing of the data is done by calling the write method of the image writer passing our instance variable of type BufferedImage to it.

Search for more Java info on this site here:
Custom Search

Please type any questions here.