Skip to main content

You are here

Capture a section of the screen using Selenium Webdriver

Capturing a section of the screen involves:

1) Performing a screen capture as usual and saving the created image to disk.
2) Getting the saved image and cutting/ cropping out a section of it as required into another image file.

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CaptureScreenSection {

public static void main(String[] args) throws IOException {
//Initialise firefox browser
WebDriver driver = new FirefoxDriver();

/* Next line makes the browser wait for 7 seconds before declaring it cant find an element.
Good for slow loading websites*/

// Step 01: Take Screen shot and create the file
System.out.println("Taking Screen Shot");
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("c:\\logicandtricks\\screenshot.jpg"));

// Step 02: Cut/ Crop out a section of the saved photo above and save the cropped photo
Image orig = File("c:\\logicandtricks\\screenshot.jpg"));
int x = 10, y = 20, w = 500, h = 510;  // define the sections to cut out
BufferedImage bi = new BufferedImage(w, h, BufferedImage.OPAQUE);
bi.getGraphics().drawImage(orig, 0, 0, w, h, x, y, x + w, y + h, null);
ImageIO.write(bi, "jpg", new File("c:\\logicandtricks\\screenshot_cropped.jpg"));






No votes yet

Add new comment

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.


Note that the codes and ideas expressed on this site are the authors personal views. The content of this website are the personal notes based on the learning experience of the author. The author will not be responsible for any error or damages resulting from you using the content of this website.

Premium Drupal Themes by Adaptivethemes