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;
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With