Interview frequency: …
Short answer
By reducing the image's dimensions at decode time using inSampleSize, recycling previous Bitmap objects through inBitmap, and relying on specialized libraries such as Coil.
Explanation
An image reserves memory based on its dimensions in pixels, not on the file size on disk (width × height × 4 bytes for ARGB_8888). If you display a 4K image inside a small 100x100 ImageView, it will consume tens of megabytes for no benefit. BitmapFactory.Options.inSampleSize specifies a precise downscale ratio that reads only the pixels needed for the screen.
Code example
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true // Read dimensions only without allocating memory
BitmapFactory.decodeFile(imagePath, this)
// Calculate the downscaling ratio based on the requested screen size:
inSampleSize = calculateInSampleSize(this, reqWidth = 200, reqHeight = 200)
inJustDecodeBounds = false
}
val safeBitmap = BitmapFactory.decodeFile(imagePath, options)Common mistakes
- Loading original high-resolution images directly into memory without computing inSampleSize.
- Writing image processing and caching code by hand instead of using a modern library such as Coil built on coroutines.