Selenium - TakesScreenshot - java - trouble converting to jpg

391 Views Asked by At

I have the following java method, which successfully creates the png file:

        TakesScreenshot scrShot = ((TakesScreenshot) webdriver);
        File SrcFile = scrShot.getScreenshotAs(OutputType.FILE);
        File DestFile = new File(fileWithPath + featureFileName + ".png");
//        BufferedImage img = ImageIO.read(SrcFile);
//        ImageIO.write(img, "jpg", new File(fileWithPath + featureFileName + ".jpg"));
        FileUtils.copyFile(SrcFile, DestFile);

I'm trying to convert the image to jpg using the 2 commented lines, but jpg output file is not being produced. No error. No file. I can't figure out why. Thanks in advance for any help.

1

There are 1 best solutions below

1
Alexey R. On

You are likely using OpenJDK that is having number of issues with JPG encoding, especially when you convert from png.

So that your workaround would be to convert image BufferedImage to another BufferedImage and then save it like:

try {
    TakesScreenshot scrShot = ((TakesScreenshot) driver);
    File SrcFile = scrShot.getScreenshotAs(OutputType.FILE);
    BufferedImage pngImage  = ImageIO.read(SrcFile);
    int height = pngImage.getHeight();
    int width = pngImage.getWidth();
    BufferedImage jpgImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    jpgImage.createGraphics().drawImage(pngImage, new AffineTransform(1f,0f,0f,1f,0,0), null);
    ImageIO.write(jpgImage, "jpg", new File("/your_path/output.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}