将javafx.scene.image.Image写入文件?

时间:2014-11-21 05:26:41

标签: java image file-io javafx

我如何将javafx.scene.image.Image图像写入文件。我知道你可以在BufferedImages上使用ImageIO,但有没有办法用javafx图像做到这一点?

2 个答案:

答案 0 :(得分:19)

首先使用BufferedImage

将其转换为javafx.embed.swing.SwingFXUtils
Image image = ... ; // javafx.scene.image.Image
String format = ... ;
File file = ... ;
ImageIO.write(SwingFXUtils.fromFXImage(image, null), format, file);

答案 1 :(得分:7)

差不多3年后,我现在有知识可以做并回答这个问题。是的,原始答案也是有效的,但它涉及首先将图像转换为BufferedImage,我理想地想完全避免摆动。虽然这确实输出了图像的原始RGBA版本,这足以满足我的需要。我实际上可以使用原始BGRA,因为我正在编写软件来打开结果,但由于gimp无法打开,我认为我将其转换为RGBA。

Image img = new Image("file:test.png");
int width = (int) img.getWidth();
int height = (int) img.getHeight();
PixelReader reader = img.getPixelReader();
byte[] buffer = new byte[width * height * 4];
WritablePixelFormat<ByteBuffer> format = PixelFormat.getByteBgraInstance();
reader.getPixels(0, 0, width, height, format, buffer, 0, width * 4);
try {
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("test.data"));
    for(int count = 0; count < buffer.length; count += 4) {
        out.write(buffer[count + 2]);
        out.write(buffer[count + 1]);
        out.write(buffer[count]);
        out.write(buffer[count + 3]);
    }
    out.flush();
    out.close();
} catch(IOException e) {
    e.printStackTrace();
}
相关问题