Selenium WebDriverの画面キャプチャ 拡張子を変える

Selenium WebDriverでキャプチャを撮って、画像ファイルに保存するときに拡張子をjpeg、giff、pngなど変えるやり方。

普通にキャプチャをファイルに保存するには

public void takeScreenShot(Path outputPath) {
    System.out.println("= Screen Shot =");
    File img = ((TakesScreenshot)this.webDriverInstance).getScreenshotAs(OutputType.FILE);
    try {
        FileUtils.copyFile(img, outputPath.toFile());
        System.out.println("Name : " + outputPath.toFile().getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

selenium-javaの依存関係にcommons-ioが入っているので、特別追加しなくてもFileUtilsを使える。

画像の拡張子を指定して画像保存する

    /**
     * 起動済みのブラウザでスクリーンショットを撮る。
     */
    public void takeScreenShot(Path outputPath) {
        System.out.println("= Screen Shot =");
        File img = ((TakesScreenshot)this.webDriverInstance).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.forceMkdirParent(outputPath.toFile());
            ImageIO.write(ImageIO.read(img), "jpeg", outputPath.toFile());
            System.out.println("Name : " + outputPath.toFile().getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

javax.imageio.ImageIOクラスで以下の拡張子に対応してるらしい。

WriterFormatNames:
BMP
bmp
jpeg
wbmp
png
JPG
PNG
jpg
WBMP
JPEG

参考

stackoverflow.com

www.javadrive.jp