Capture screenshots
7 January 2008Talking screenshots in windows is simple and very useful in our day to day business. It is done by pressing the Print Screen key on your keyboard [PrtScn], pasting it in image editor such as MS paint and then editing and saving it. In this post, I will write about how to do this from Java program.
Java provides classes to help us which capturing screens.
java.awt.Robot is used to generate native system input events which can be used to for test automation, and other applications where control of the mouse and keyboard is needed. We will used Robot class to capture a rectangle area of the screen. We will use following method to read and capture pixels from the screen mentioned as rectangle.
BufferedImage createScreenCapture(Rectangle screenRect)
Also we will use javax.imageio.imageIO class for saving the image on the disk in the required format. We will be using the following method to write the image file on the disk:
static boolean write(RenderedImage im, String formatName, File output)
Time for demonstration:
try { Robot robot = new Robot(); BufferedImage bi=robot.createScreenCapture(new Rectangle(400,600)); ImageIO.write(bi, "jpg", new File("C://screens//img1.jpg")); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
We mentioned the area to capture as rectangle. The images will be capture and will be stored as a jpeg file in the file system.
Happy coding!
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Capture screenshots