Friday 1 November 2013

Generate a screenshot in Java

Under ubuntu,

1. Install firefox and virtual framebuffer
sudo aptitude install xvfb firefox
2. Write Java code:
import java.io.File;
import java.io.IOException;

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.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CaptureScreenshotTest{
   private static int DISPLAY_NUMBER = 99;
   private static String XVFB = "/usr/bin/Xvfb";
   private static String XVFB_COMMAND = XVFB + " :" + DISPLAY_NUMBER;
   private static String URL = "http://www.google.com/";
   private static String RESULT_FILENAME = "/tmp/screenshot.png";

   public static void main ( String[] args ) throws IOException{
     Process p = Runtime.getRuntime().exec(XVFB_COMMAND);
     FirefoxBinary firefox = new FirefoxBinary();
     firefox.setEnvironmentProperty("DISPLAY", ":" + DISPLAY_NUMBER);
     WebDriver driver = new FirefoxDriver(firefox, null);
     driver.get(URL);
     File scrFile = ( (TakesScreenshot) driver ).getScreenshotAs   (OutputType.FILE);
     FileUtils.copyFile(scrFile, new File(RESULT_FILENAME));
     driver.close();
     p.destroy();
   }
}



3. Get the following jars:
selenium-java-2.37.0.jar
commons-io-2.4.jar
guava-15.0.jar
json-jena-1.0.jar
commons-exec-1.1.jar
httpcore-4.3.jar
httpclient-4.3.jar
commons-logging-1.1.1.jar

4. Compile
javac -cp /jars/selenium-java-2.37.0.jar:/jars/commons-io-2.4.jar:. CaptureScreenshotTest.java


5. Run
java -cp /jars/selenium-java-2.37.0.jar:/jars/commons-io-2.4.jar:/jars/guava-15.0.jar:/jars/json-jena-1.0.jar:/jars/commons-exec-1.1.jar:/jars/httpcore-4.3.jar:/jars/httpclient-4.3.jar:/jars/commons-logging-1.1.1.jar:. CaptureScreenshotTest


No comments:

Post a Comment