Monday, June 29, 2015

CAPTURE A SECTION OF 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.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
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*/
driver.manage().timeouts().implicitlyWait(7,TimeUnit.SECONDS);
driver.get("http://www.sojicity.com/"); 

// 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 = ImageIO.read(new 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"));

}





Credits: http://www.logicandtricks.com/

2 comments:

  1. As for me, i prefer to wait for certain conditions ro be met rather than waiting for a,predifined seconds. Remember to wait minimum one second before starting the infinite loop though. Anyways. Thx for the code. 😃

    ReplyDelete
    Replies
    1. You are absolutely correct. I will include the same as post and also going forward I will try to put the code snippets with these good practices. I was just being lazy as topic was different here. You have sharp eyes ;)

      Delete