0

我有以下java方法,它成功创建了png文件:

        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);

我正在尝试使用 2 条注释行将图像转换为 jpg,但jpg没有生成输出文件。没有错误。无文件。我不知道为什么。提前感谢您的帮助。

4

1 回答 1

1

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();
}
于 2021-11-02T09:59:33.567 回答