Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing javafx.scene.image.Image to file?

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?

like image 720
Scoopta Avatar asked Nov 21 '14 05:11

Scoopta


2 Answers

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);
like image 174
James_D Avatar answered Nov 20 '22 14:11

James_D


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();
}
like image 28
Scoopta Avatar answered Nov 20 '22 14:11

Scoopta