I need to let the user open a specific album from their gallery, and let them to do something with images.
In order to retrieve an image from an album, I’m using:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri).
Everything works fine, except the fact that if the album contains many pictures, it ends up trowing an OutOfMemoryException.
Now, I know how to mitigate this issue based on Android guidelines, but the problem is that I’m already retrieving the original Bitmap with getBitmap()
So, is there a possibility to retrieve the image in the byte array format, or an input stream format, and scale it down before assigning it in memory to avoid memory leaks? (in the same way the Android guidelines advice)
So, having a image
Uriin my hands I wanted to retrieve it’sInputStreamand scale down the image before assigning it in memory to avoidOutOfMemoryExceptionSolution:
To retrieve the InputStream from an Uri, you have to call this:
Then following Android recommendations on loading bitmaps efficiently, you just need to call
BitmapFactory.decodeStream(), and pass theBitmapFactory.Optionsas a parameter.Full source code:
Helper methods: