How to take a screenshot using Robot

Java Cup
Here is an example on taking a screenshot in Java using the AWT Robot class which is earlier discussed in this blog. You do not need to write tonnes and tonnes of code to do this, it is just a method far way. The method that does the thing is createScreenCapture() present in java.awt.Robot class. Here is it's prototype.

BufferedImage createScreenCapture(Rectangle rect)

This method takes java.awt.Rectangle as parameter. You can use any of the seven constructors of this class to create it's object, however i don't recommend the first one which just creates a Rectangle object that is invisible when used to capture the screen. All the constructors do the same thing, their parameters differ instead. For brevity and ease, in this post i will be using the third constructor which takes 4 integer values which represent the x, y, width, height respectively. The returned java.awt.image.BufferedImage object is returned. This is used to write the image to a file. Here is the example.


import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
class ScreenCapture
{
public static void main(String args[]) throws Exception
{
// Throws AWTException
Robot rb=new Robot();

Scanner s=new Scanner(System.in);
System.out.println("Enter the x,y,width,height of capture");
int x=s.nextInt();
int y=s.nextInt();

int width=s.nextInt();
int height=s.nextInt();

String file=s.next();

// Get the BufferedImage object for writing to a fiel
BufferedImage bim=rb.createScreenCapture(new Rectangle(x,y,width,height));

/* Throws IOException
* Write in PNG format. You can choose whatever format you want.
* Write the image.
* If you know the extension of the format.
* Write to a file specified
*/
ImageIO.write(bim,"PNG",new File(file));
}
}

Sample output of ScreenCapture

Creating ScreenShot in Java using Robot class

No comments: