I\'m trying to create a simple image editing program in java. I made an ImageCanvas
object that has all the information about the image that is being edited (so
Serialization is pretty straight-forward in that it persists static data. You are otherwise in the right place with read/write object in the Serialization family of methods. Think about what a "BufferedImage" is. It is a buffered streaming implementation. To serialize, the data must be flushed out to a static object like a byte[] array and then THAT object may be serialized/deserialized into/out of a BufferedImage such that the buffered streaming now comes in/out of that byte[] array.
make your ArrayList<BufferedImage>
transient, and implement a custom writeObject()
method. In this, write the regular data for your ImageCanvas, then manually write out the byte data for the images, using PNG format.
class ImageCanvas implements Serializable {
transient List<BufferedImage> images;
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(images.size()); // how many images are serialized?
for (BufferedImage eachImage : images) {
ImageIO.write(eachImage, "png", out); // png is lossless
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
final int imageCount = in.readInt();
images = new ArrayList<BufferedImage>(imageCount);
for (int i=0; i<imageCount; i++) {
images.add(ImageIO.read(in));
}
}
}