Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Image serialization

Is there any way to serialize javafx.scene.image.Image?

I found only one method: create own serializable class which stores image data in pixel format(byte[][]). I can not believe that JavaFX have no built-in mechanism for image serialization.

Here is my SerializableImage class.

import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;

import java.io.Serializable;


public class SerializableImage implements Serializable {
    private int width, height;
    private int[][] data;

    public SerializableImage() {}

    public void setImage(Image image) {
        width = ((int) image.getWidth());
        height = ((int) image.getHeight());
        data = new int[width][height];

        PixelReader r = image.getPixelReader();
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                data[i][j] = r.getArgb(i, j);
            }
        }

    }

    public Image getImage() {
        WritableImage img = new WritableImage(width, height);

        PixelWriter w = img.getPixelWriter();
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                w.setArgb(i, j, data[i][j]);
            }
        }

        return img;
    }

}
like image 356
Ivan Avatar asked Jan 08 '23 09:01

Ivan


1 Answers

Typically you would persist (or stream) an image by storing it in a regular image format, which you can do by creating a java.awt.image.BufferedImage representation and using the javax.imageio.ImageIO API:

Image image = ... ;
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", ...); 

The third argument to ImageIO.write(...) can be a File or OutputStream.

If you have some class you want to make serializable, which contains an Image, you can create a custom serialized form:

public class SomeClass implements Serializable {
    private transient Image image ;

    // other fields, etc...

    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
        s.defaultReadObject();
        image = SwingFXUtils.toFXImage(ImageIO.read(s), null);
    }

    private void writeObject(ObjectOutputStream s) throws IOException {
        s.defaultWriteObject();
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", s);
    }
}
like image 143
James_D Avatar answered Jan 16 '23 06:01

James_D