Monday, August 5, 2019

How to take screen shots in Java

This tutorial explains how to take screen shots in Java with simple example. 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. This example takes the screen shot of your desktop and save it in a PNG file. The screen shot will be stored in the file that you specified in argument.

How to take screen shots in Java

How to take screen shots in Java

Lets see the below example, that helps to take screen shots in Java with simple example.

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;


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));


This is all about How to take screen shots in Java. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment