How to serialize an object that includes BufferedImages

前端 未结 2 1874
醉酒成梦
醉酒成梦 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 07:07

    make your ArrayList 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 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(imageCount);
            for (int i=0; i

提交回复
热议问题