How to serialize an object that includes BufferedImages

前端 未结 2 1858
醉酒成梦
醉酒成梦 2020-11-27 06:26

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

相关标签:
2条回答
  • 2020-11-27 06:52

    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.

    0 讨论(0)
  • 2020-11-27 07:07

    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));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题