How to take screen shots in Java

how to take screenshots in java

While surfing through internet, I came to this amazing piece of code in Java that takes the screen shot of your desktop and save it in a PNG file.

This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation.

Copy and paste following code in your Java class and invoke the method captureScreen() with file name as argument. The screen shot will be stored in the file that you specified in argument.

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

...

public void captureScreen(String fileName) throws Exception {

   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));

}
...


6 Comments

  • Suresh G wrote on 16 February, 2009, 10:33

    See this site http://www.screencast-o-matic.com/
    It uses the Robot class to create the screen cast

  • Viral Patel wrote on 18 February, 2009, 14:45

    Thanks Suresh for the link.

  • Chetan wrote on 25 March, 2010, 12:28

    Great!!!!!

  • prashant ingale wrote on 24 December, 2011, 21:18

    i have managed to take screenshot but i am failing to display it . It gives nullpointerexception for following code
    JPanel p=new JPanel();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle screenRectangle = new Rectangle(screenSize);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(screenRectangle);
    ImageIcon img=(ImageIcon)image;
    Image im=img.getImage();
    Graphics g;
    g.drawImage(im,0,0,p);

    plz help me…………….

  • Josh wrote on 18 March, 2012, 3:13

    Change it to :

    g.drawImage(im, 0, 0, p, this);

  • Wes wrote on 20 April, 2012, 6:28

    Eclipse showed major errors it ddint work at all..

Leave a Reply

Your email address will not be published. Required fields are marked *

*