以jpg格式保存在JavaFX中的图像是粉红色的

时间:2013-10-23 17:24:54

标签: image save png javafx jpeg

我想将ImageView中的图像保存到具有不同分辨率的文件中。像.png那样按预期结果。至于.jpg - 我得到所有文件粉红色调。

should be blue

诀窍在哪里?这是代码:

Object[] imagesFromFotoListView = ta.myFotoListView.getItems().toArray();
new File(localDir).mkdirs();
for (int i = 0; i < imagesFromFotoListView.length; i++) {
    new File(localDir + "/" + i).mkdirs(); 
    final ImageView iv = new ImageView((Image) imagesFromFotoListView[i]);
    ImageIO.write(SwingFXUtils.fromFXImage(iv.snapshot(null, null), null), "jpg", new File(localModelFotoDir + "/" + i + "/large.jpg")); // JPG THAT FAILS PINK.
    BufferedImage bi = SwingFXUtils.fromFXImage(iv.snapshot(null, null), null);
    int resolution[] = new int[]{500, 250, 75};
    for (int j = 0; j < resolution.length; j++) {
        BufferedImage resizedBImage;
        if (bi.getWidth() == bi.getHeight()) {
            resizedBImage = resizeBufferedImage(bi, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.AUTOMATIC, resolution[j], resolution[j]);
        } else if (bi.getWidth() > bi.getHeight()) {
            resizedBImage = resizeBufferedImage(bi, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.AUTOMATIC, resolution[j], (int) ((double) resolution[j] * bi.getHeight() / bi.getWidth()));
        } else {
            resizedBImage = resizeBufferedImage(bi, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.AUTOMATIC, (int) ((double) resolution[j] * bi.getWidth() / bi.getHeight()), resolution[j]);
        }
        Image resizedI = (Image) SwingFXUtils.toFXImage(resizedBImage, null);
        ImageIO.write(SwingFXUtils.fromFXImage((Image) SwingFXUtils.toFXImage(resizedBImage, null), null), "png", new File(localModelFotoDir + "/" + i + "/" + resolution[j] + ".png")); // PNG THAT GOES WELL
    }
}

2 个答案:

答案 0 :(得分:18)

我在Oracle论坛上找到了一个解决方案。正如广泛讨论的那样,问题在alpha-channel 中需要从源图像中排除,目标是.jpg save。我还重新安排了我的代码,使其更短。解决方法是:

// Get buffered image:
BufferedImage image = SwingFXUtils.fromFXImage(myJavaFXImage, null); 

// Remove alpha-channel from buffered image:
BufferedImage imageRGB = new BufferedImage(
    image.getWidth(), 
    image.getHeight(), 
    BufferedImage.OPAQUE); 

Graphics2D graphics = imageRGB.createGraphics();

graphics.drawImage(image, 0, 0, null);

ImageIO.write(imageRGB, "jpg", new File("/mydir/foto.jpg"));

graphics.dispose();

已在Java 8中修复:https://bugs.openjdk.java.net/browse/JDK-8114609

答案 1 :(得分:1)

更新

此问题已针对Java 8修复:

JDK-8114609 Incorrect display of JPEG images


看起来您遇到了ImageIO或JavaFX图像处理库中的现有错误。

您可能希望尝试下面的StackOverflow问题中建议的一些解决方法,看看是否有任何问题可以解决您的问题: