OutOfMemoryError while decoding and encoding Base64 String into Bitmap

前端 未结 7 2025
你的背包
你的背包 2020-12-14 14:49

I\'m trying to decode and encode a Bitmap image. On some devices it runs perfectly while on others it\'s not. I\'m uploading Bas

7条回答
  •  别那么骄傲
    2020-12-14 15:21

    I would suggest you to:

    1. If you receive data from a server using xml-based protocol - use SAX parser instead of DOM.

    2. Do not load the whole base64 string in to the memory. Use InputStream to load portion of data in to the byte[] array, decode Base64 from the array and append the result to a cache file via FileOutputStream.

    3. Use options.inJustDecodeBounds option to prevent a full-scale bitmap file loading in to the memory. You can evaluate the total amount of memory required and make a decision to scale it down, for example. UPD. I noticed you are using it already.

    4. Keep in mind object references you are holding and passing trough your methods flow. Strong references prevents memory from to be reclaimed by GC.

    Following your code: method decodeBase64 holds String input argument parameter in the stack, byte[] decodedBytereference and return BitmapFactory.decodeStream(new FileInputStream(f), null, o2) at the very end. Holding all these objects in the memory at the same time means big pressure on GC and memory allocation in general. As a simplest solution you can null references just after corresponding objects were used (string and byte array), so GC will be able to free up them.

提交回复
热议问题