Home Code How to Take Screenshot and Save to MSSQL Database using Java and...

How to Take Screenshot and Save to MSSQL Database using Java and Selenium Webriver

This is to take Screenshot using Selenium Webdriver and to save in MS SQL Database. The image is saving in the database with the image name append with browser name, browser version, sequence number, and scenario name. This code is supported by Chrome, Firefox, Internet Explorer, and Safari.

There is one more option between line 63-70 to save the picture into a local folder if you want. You can set a folder in the local system and it will save the picture into the folder you specified in png format and byte format in MSSql Database.

Take Screenshot and save to MSSQL Database using Java and Selenium Webriver

package com.main;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;

public class ImageSave {
private static int imageSeqNo = 0;
private static String scenName;
private static WebDriver browserDriver;
private static int browserWidth;
private static int browserHeight;
public static String browser;
public static WebDriver driver;

public static int getBrowserWidth() {
return browserWidth;

public static int getBrowserHeight() {
return browserHeight;

public static String getScenName() {
return scenName;

public static int getImageSeqNo() {
return imageSeqNo;

public static void main(String[] args) throws Exception {
// BrowserDriver.getCurrentDriver();

public static void addScreenshot(WebDriver driver) throws IOException,
ClassNotFoundException, InterruptedException {

byte[] scrByte = getScreenShotBytes(driver);

browser = getBrowserAndVersion();
String scenarioName = getScenName();
String imageName = scenarioName + ” ” + browser + ” ”
+ System.currentTimeMillis() + “.png”;

File scrFile = getScreenShotFile(driver);
String screenWidthHeight = getImageWidthHeight(scrFile);
// if want to save screen shot picture in local system, enable line below
// FileUtils.copyFile(scrFile, new File(“C://screenshot//” + imageName));
insertImageDB(scrByte, scenarioName, imageName, screenWidthHeight,

public static String getImageWidthHeight(File imageFile) throws IOException {
BufferedImage bimg = ImageIO.read(imageFile);
int imageWidth = bimg.getWidth();
int imageHeight = bimg.getHeight();
if (imageWidth != 0) {
return imageWidth + “x” + imageHeight;
} else {
return “FullScreenx” + imageHeight;


public static File getScreenShotFile(WebDriver driver) {
// WebDriver driverA = new Augmenter().augment(driver);
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

public static byte[] getScreenShotBytes(WebDriver driver) {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);

public static void insertImageDB(byte[] imageByte, String scenName,
String imageName, String screenWidthHeight, String browser)
throws ClassNotFoundException {
Properties dbProp = new Properties();
InputStream dbPropInput = null;
ResultSet rs = null;
PreparedStatement ps = null;
Connection con = null;
//setImageSeqNo(getImageSeqNo() + 1);
int seqNo = getImageSeqNo();
System.out.println(scenName + ” —- ” + browser + ” —- ”
+ screenWidthHeight + ” —- Shot Number: ” + seqNo);

try {
String propPath = “.\src\test\resources\props\dbConnect.properties”;
dbPropInput = new FileInputStream(propPath);
dbProp.load(dbPropInput); // load property file
String dbDriver = (dbProp.getProperty(“dbDriver”));
String dbURL = (dbProp.getProperty(“dbURL”));
String stPro = (dbProp.getProperty(“SPSql”));

con = DriverManager.getConnection(dbURL);
ps = con.prepareStatement(stPro);

java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date.getTime());
System.out.println(“Image Timestamp=” + sqlTimestamp);

ps.setQueryTimeout(90); // timeout value may disable later, picture

ps.setString(1, “Project”);
ps.setString(2, scenName);
ps.setString(3, browser);
ps.setString(4, screenWidthHeight);
ps.setTimestamp(5, sqlTimestamp);
ps.setInt(6, seqNo);
ps.setString(7, imageName);
ps.setBytes(8, imageByte);
// comment below line to disable data base updating

} catch (IOException e) {
} catch (SQLException e) {
} finally {
try {
if (dbPropInput != null)
if (rs != null)
if (ps != null)
if (con != null)
} catch (Exception e) {

public static String getBrowserAndVersion() {
String browser_version = null;
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
String browsername = cap.getBrowserName();
// This block to find out IE Version number
if (“internet explorer”.equalsIgnoreCase(browsername)) {
String uAgent = (String) ((JavascriptExecutor) driver)
.executeScript(“return navigator.userAgent;”);
// uAgent return as “MSIE 8.0 Windows” for IE8
if (uAgent.contains(“MSIE”) && uAgent.contains(“Windows”)) {
browser_version = uAgent.substring(uAgent.indexOf(“MSIE”) + 5,
uAgent.indexOf(“Windows”) – 2);
} else if (uAgent.contains(“Trident/7.0”)) {
browser_version = “11.0”;
} else {
browser_version = “00”;
} else {
// Browser version for Firefox and Chrome
browser_version = cap.getVersion();// .split(“.”)[0];
String browserversion = browser_version.substring(0,
String bVersion = String.format(“%02d”, Integer.parseInt(browserversion));
return ((browsername) + “_” + bVersion);

public static String browserNameConvert(String browser_name) {
if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “explorer”)) {
return “IE”;
} else if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “firefox”)) {
return “FF”;
} else if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “chrome”)) {
return “CH”;
} else if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “safari”)) {
return “SF”;
} else {
return “NA”;

How to Convert Picture into Byte, Get Image Width and Height using Java

MSSQL Database Connection Property file with user credentials and Store Procedure

SPSql={call STOREPROCEDURE (?,?,?,?,?,?,?,?)}

To save in database, the store procedure already created in this example and all these data for database connection and store procedure is listed in the property file.

The browser name converting to 2 char short forms like FF(Firefox), CH (Chrome) etc. This is also capable of finding browser version programmatically including Internet Explorer version number. This script supports Internet Explorer versions 8,9,10,11.

Disclaimer: MashTips is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission at no extra cost to you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Free Newsletter


Best Google Lite Apps for Low End Android Phones with Slow Internet.

First of all, an app is labeled "Lite" when the original version is stripped down of its resource-hungry components and made thoroughly basic. And...

6 Free iOS Apps to Stream Music from Cloud in Offline

Now we are entering into the world of cloud storage in place of memory cards and external storage. iOS music app can stream music...

Get Safari Reader Feature in Chrome and FireFox for A Clean Webpage

The Safari browser offers a nice reading feature to read web pages comfortably called Reader. In Safari, the Readable button filters out all advertisements,...

How to Install Custom Watch Faces on Your Amazfit GTR with iPhone

There are tons of custom watch faces available for Amazfit's GTR and other Smartwatch models. Instead of using your GTR's default watch face, you...

How to Import Google WiFi Networks to Google Home

Google brings a new update with Google Home App to integrate Google WiFi to Google Home. This update will help you to control all...

How to add printer to the domain?

In order to add the printer to the domain, you'll have to share it from a print server first (A print server that is...