I need to capture the screenshot of a Web Element...Here is the code I am using..but unsuccessful...Code is breaking at this statement.. BufferedImage destImage = bufferedImage.getSubimage(P.getX(), P.getY(), rectangle.width, rectangle.height);
public void takeScreenshotElement(WebDriver driver, WebElement element) throws IOException {
File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Point P = (Point) element.getLocation();
int width =element.getSize().getWidth();
int height = element.getSize().getHeight();
Rectangle rectangle = new Rectangle(width, height);
BufferedImage bufferedImage = ImageIO.read(screenShot);
try{
BufferedImage destImage = bufferedImage.getSubimage(P.getX(), P.getY(), rectangle.width, rectangle.height);
ImageIO.write(destImage, "png", screenShot);
File file = new File("//path//to");
FileUtils.copyFile(screenShot, file);
} catch(RasterFormatException ignoRasterFormatException)
{
System.out.println("Ignore Exception");
}
}
Instructor
Ashish Thakur Replied on 13/11/2019
This code works perfectly for me. You can just change path of the screenshot file
package goodones;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebElementScreenshot {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
WebElement element = driver.findElement(By.id("login1"));
File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Point P = (Point) element.getLocation();
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
Rectangle rectangle = new Rectangle(width, height);
BufferedImage bufferedImage = ImageIO.read(screenShot);
try{
BufferedImage destImage = bufferedImage.getSubimage(P.getX(), P.getY(), rectangle.width, rectangle.height);
ImageIO.write(destImage, "png", screenShot);
File file = new File("D:\\test.png");
FileUtils.copyFile(screenShot, file);
} catch(RasterFormatException ignoRasterFormatException)
{
System.out.println("Ignore Exception");
}
}
}