André L. S. Softwares Development, Technology and Games

17Sep/090

Taking Screen Shots with Java

Here I'll show how to implements a class to take Screen shots.

I thinking about the complexity of a class that takes screen shots and store the files in hard disk and, asking to "uncle G", I fonded the class Robot, that provide createScreenCapture method.

Now I'll show how to implement this functionality:

Robot robot = new Robot();
//Setting the rectangle that mark capture area. In this case, will be all screen..
Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

BufferedImage img = robot.createScreenCapture(rect);

Here we defined capture area and obtained a BufferedImage, our image. Now, we needed to persist in hard disk.

//Capturing the ImageWriter and ImageWriterParam
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam iwp = writer.getDefaultWriteParam();

//Setting compression mode and the image quality
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);

//Persisting the image
writer.setOutput(new FileImageOutputStream(arquivo));

IIOImage iioimage = new IIOImage(img, null, null);

writer.write(null, iioimage, iwp);
writer.dispose();

We captured the ImageWriter and ImageWriterParam to set the compression method and the image quality.

In line 07 we defined the image quality as 1, where the value can be between 0 (zero), more compression and less quality and 1 (one), less compression and more quality. Then we have kept the file in HD.

We've done! Simple, isn't?

Download this sample here.

See ya!

Tagged as: , , , No Comments