JavaFX 图像序列化 [英] JavaFX Image serialization
问题描述
有没有办法序列化javafx.scene.image.Image?
我只找到了一种方法:创建自己的可序列化类,以像素格式(字节[][])存储图像数据.我不敢相信 JavaFX 没有内置的图像序列化机制.
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.
这是我的 SerializableImage 类.
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;
}
}
推荐答案
通常,您可以通过以常规图像格式存储图像来持久化(或流式传输)图像,您可以通过创建一个 java.awt 来实现.image.BufferedImage
表示和使用 javax.imageio.ImageIO
API:
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", ...);
ImageIO.write(...)
的第三个参数可以是 File
或 OutputStream
.
The third argument to ImageIO.write(...)
can be a File
or OutputStream
.
如果你有一些类想要序列化,其中包含一个Image
,你可以创建一个自定义的序列化表单:
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);
}
}
这篇关于JavaFX 图像序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!