Serializing and De-Serializing android.graphics.Bitmap in Java

后端 未结 3 677
后悔当初
后悔当初 2020-11-28 13:55

I have started work on an my first android application and have the basis of an application that handles an image with multiple layers. I am able to export a flat version of

3条回答
  •  隐瞒了意图╮
    2020-11-28 14:27

    Here is an example of a serializable object that can wrap bitmaps.

    public class BitmapDataObject implements Serializable {
    
        private Bitmap currentImage;
    
        public BitmapDataObject(Bitmap bitmap)
        {
            currentImage = bitmap;
        }
    
        private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            currentImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
    
            byte[] byteArray = stream.toByteArray();
    
            out.writeInt(byteArray.length);
            out.write(byteArray);
    
        }
    
        private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    
    
            int bufferLength = in.readInt();
    
            byte[] byteArray = new byte[bufferLength];
    
            int pos = 0;
            do {
                int read = in.read(byteArray, pos, bufferLength - pos);
    
                if (read != -1) {
                    pos += read;
                } else {
                    break;
                }
    
            } while (pos < bufferLength);
    
            currentImage = BitmapFactory.decodeByteArray(byteArray, 0, bufferLength);
    
        }
    }
    

提交回复
热议问题