Writing javafx.scene.image.Image to file?


Question

How would I go about writing a javafx.scene.image.Image image to a file. I know you can use ImageIO on BufferedImages but is there any way to do it with a javafx Image?

1
13
11/21/2014 5:26:40 AM

Accepted Answer

Almost 3 years later and I now have the knowledge to do and answer this. Yes the original answer was also valid but it involved first converting the image to a BufferedImage and I ideally wanted to avoid swing entirely. While this does output the raw RGBA version of the image that's good enough for what I needed to do. I actually could just use raw BGRA since I was writing the software to open the result but since gimp can't open that I figure I'd convert it to 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();
}
8
6/30/2017 11:37:55 PM

Just convert it to a BufferedImage first, using javafx.embed.swing.SwingFXUtils:

Image image = ... ; // javafx.scene.image.Image
String format = ... ;
File file = ... ;
ImageIO.write(SwingFXUtils.fromFXImage(image, null), format, file);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon