This small chunk of code will help you to take a screenshot of entire screen on any platform. It is especially helpful in test automation frameworks to add "take a screenshot on failure" functionality.
captureScreen method accepts the filename of the image to be produced in PNG format including the full path (absolute or relative to the working directory), e.g. "out/screenshots/myscreen.png"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 class Screenshot { | |
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)); | |
} | |
} |