Topics
Recent articles

Android & Mobile

How to Choose Bitmap inSampleSize on Low-RAM Android Devices

Calculate Android bitmap sample size from the target view, estimate pixel memory, and test peak allocations on constrained devices.

Table of Contents8 sections
Pixel art compares a 4000 by 3000 photo decode with a 1000 by 750 decode at sample size four.
Sample size 4 uses roughly one sixteenth as many pixels before any exact resizing.

A compressed photo can fit comfortably in storage and still be expensive to render. For a 4000 × 3000 photo going into an 800 × 600 preview, the quickest memory win is to decode fewer pixels in the first place.

Quick solution:

Read the source bounds without allocating pixels. Choose the largest power of two that keeps enough pixels for the display, then decode from a fresh stream off the UI thread.

4000 × 3000 photo → 800 × 600 target
inSampleSize = 4 → approximately 1000 × 750, 2.86 MiB at 4 bytes/pixel
inSampleSize = 8 → approximately 500 × 375, too small for this target

The sample is chosen for the target and source, not from a rule that every device with 1 GB of RAM should use the same value.

Start with display pixels, not file size or device RAM

The file’s byte count measures the compressed representation. Decoding expands it into a pixel buffer. At four bytes per pixel, a 4000 × 3000 image requires 48,000,000 bytes for pixels, or about 45.78 MiB. A solid-color image and a noisy image can have very different JPEG sizes even though their decoded dimensions and pixel configuration match. A limit on download bytes is not a substitute for checking the bounds before decode.

Measure the rendered content area in physical pixels. An Android layout size expressed in density-independent pixels is a sizing input, not necessarily the number of pixels to decode. Likewise, a screen-width thumbnail does not need the same target as a preview you can zoom. Measure the view when its size is known, or let an image loader resolve the target. If the intent is to print or edit a full-resolution original, preserve that original separately rather than increasing the preview bitmap.

A device with 1 GB of physical RAM shares it with the operating system and other processes. The app does not get a 1 GB bitmap budget. ActivityManager documentation describes the approximate app memory class and a separate low-RAM indicator. They are useful context for picking representative devices, not an allocation guarantee. Start from a reasonable target, then measure the peak in the actual flow.

Pick the largest usable power of two

The BitmapFactory.Options documentation explains that a sample size of two asks for roughly half of each dimension, or one quarter of the pixels. It also notes that decoding rounds a non-power-of-two value down to a power of two. Using explicit powers of two avoids mistaking a requested factor of three for the result you would get with exact resizing.

Sample size Approximate decoded dimensions Pixel bytes at 4 bytes per pixel Enough for 800 × 600?
1 4000 × 3000 45.78 MiB Yes, but unnecessarily large
2 2000 × 1500 11.44 MiB Yes
4 1000 × 750 2.86 MiB Yes
8 500 × 375 0.72 MiB No

Pick the largest usable step, not the closest number in the sequence. Four is the largest step that still covers both requested axes in the same-aspect example. The next step saves more memory but forces an upscale at display time. Verify actual output width and height when behavior depends on exact dimensions, especially when encoded sizes are not divisible by the sample factor. Actual pixel allocation is not necessarily the simple estimate shown in this table.

Read bounds and decode without loading the original bitmap

Use inJustDecodeBounds to get the dimensions without allocating decoded pixels, as shown in Android’s large bitmap guide. A stream used to read the header generally cannot be handed to the second decode at its current position. Make the input reopenable for both passes. For a local content URI, that can be a fresh stream supplied by the content resolver each time. For a network response that cannot be reopened reliably, use an image loader or an appropriately managed local cache rather than fetching two potentially different versions.

This Kotlin example accepts a source-aligned minimum decoded size. It does not rotate or transform the resulting bitmap. Place it in an I/O or decode worker, not the UI thread.

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.InputStream

fun chooseSample(w: Int, h: Int, minW: Int, minH: Int): Int {
    require(w > 0 && h > 0 && minW > 0 && minH > 0)
    var sample = 1
    while (sample <= Int.MAX_VALUE / 2) {
        val next = sample * 2
        if (w / next < minW || h / next < minH) break
        sample = next
    }
    return sample
}

fun decodePreview(
    open: () -> InputStream?,
    minW: Int,
    minH: Int
): Bitmap? {
    require(minW > 0 && minH > 0)
    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
    val first = open() ?: return null
    first.use { BitmapFactory.decodeStream(it, null, bounds) }

    if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
    val options = BitmapFactory.Options().apply {
        inSampleSize = chooseSample(bounds.outWidth, bounds.outHeight, minW, minH)
        inPreferredConfig = Bitmap.Config.ARGB_8888
        inScaled = false
    }
    val second = open() ?: return null
    return second.use { BitmapFactory.decodeStream(it, null, options) }
}

The multiplication guard keeps the next sample within the integer range. Integer division makes the estimate conservative near a threshold. The function returns sample 1 if the original is already smaller than the minimum along either axis; it does not invent detail by upscaling. A provider can fail to open a file or throw an I/O or permission exception. Handle expected failures at the call site and show a fallback state. Returning null here is not a guarantee that all decoding failures are swallowed.

Account for fit, crop, and photo orientation

The example has a matching source and target aspect ratio. For a wider source, using both raw view dimensions as the minimum for a fit preview can request more pixels than you display. Suppose a 4000 × 2000 photo goes into an 800 × 600 box. To fit it without cropping, the displayed area is 800 × 400. Sample four delivers about 1000 × 500, which is enough. For a center crop filling the same box, the rendered image needs the equivalent of 1200 × 600 before clipping. The same sample would undershoot, so the conservative power-of-two choice is two.

Calculate the fit or crop dimensions explicitly. To fit, use the smaller ratio between target and source axes; to fill and crop, use the larger. Round the requested source-aligned dimensions up where a fractional value matters. If the source cannot meet the target without upscaling, keep sample 1 or choose a product behavior that permits a smaller result. Cropping the final drawable does not necessarily save decoded memory, since a crop can still start from the full sampled bitmap.

Photos may have orientation metadata. Work from the oriented aspect ratio when planning the display. If your decoder reports encoded axes and the picture rotates by 90 or 270 degrees, swap the requested axes before comparing them with those encoded dimensions, and handle the orientation when presenting the bitmap. Otherwise a portrait preview might use a size chosen for a landscape layout. Use a loader that respects metadata when you do not need to own that handling.

Estimate the peak, not just one decode

Sample four brought the example from roughly 46 MiB to roughly 3 MiB of estimated pixels. That is a useful difference, but it describes one decoded buffer. A screen that preloads six at once can retain roughly 17 MiB of estimated pixels before counting existing images, temporary allocations, or other work. If the app resizes each sampled bitmap into a new 800 × 600 bitmap, the old and new buffers can coexist during the transform.

For display, prefer scaling the sampled bitmap in the view if no consumer requires an exact output file. When you do need an exact-sized result, estimate the two buffers together at their point of overlap. Keep concurrent decodes and prefetch within a measured budget. Cancel or ignore obsolete requests when the target leaves the screen, and do not make a cache retain full-resolution sources simply because they were available.

Use the Bitmap API to check allocation size where available on supported Android versions, alongside the decoded dimensions and configuration. inPreferredConfig is a request, not proof of what every decoder returned. Allocation size reflects backing storage and may differ from a simple width times height estimate. Also profile the actual process during fast scrolling or screen transitions, since a series of retained references can matter more than the smallest steady-state reading.

Choose an image loader unless you need manual control

A maintained image loader is often the better default for a feed or gallery. Let it manage request lifecycle, cache byte limits, and view sizing. Test that it actually receives a bounded request in your UI. If a wrapper always requests the original size or starts before a layout resolves, adding a loader does not remove the underlying sizing problem. Use the manual approach when you need a predictable offline decode path, have a custom processing stage, or are measuring exactly where the peak occurs.

Prefer separate policies for thumbnails and for an explicit zoom or export action. The thumbnail can use a bounded memory cache and sampled dimensions. A zoom detail can request a higher resolution only while visible, and a large editable image may need a different pipeline altogether. Keep the compressed source in storage if it is needed later. The same budget should not silently grow every time a feature needs more detail on a separate screen.

For a broader checklist, see Android memory optimization on low-RAM devices. Downsampling targets one category of memory usage; it will not solve retained activities, oversized models, or a process that is killed because the device is under pressure for other reasons.

A cache entry also needs a size identity. If you manually cache both preview and detail images, do not key both only by URI. A subsequent detail request might reuse a small preview, or an inexpensive thumbnail request might keep the larger bitmap alive. Include the target or size class and any orientation or transformation that changes the result. Decide which layer owns eviction, and avoid building a second unbounded cache in view state or a repository on top of the loader. When content at the same URI can change, use an appropriate revision or invalidation policy.

For example, you can start by limiting a thumbnail screen to one in-flight decode on the constrained device and compare it with two. Do not choose the setting from throughput alone. Check how quickly the first visible preview arrives, how much unnecessary work happens when a user flings past several rows, and whether switching to the detail screen creates a peak. If two simultaneous decodes run faster in isolation but reserve pixels for rows already offscreen, bound the queue or prioritize visible requests before increasing parallelism.

Verify with a small regression matrix

Pick a representative constrained device and run the same release-like build for before and after measurements. Check a normal camera image, a wide photo, a photo with rotated metadata, and a missing or undecodable file. Confirm the requested dimensions are in pixels and the rendered result still looks acceptable at the actual size. Test the highest-impact workflow, such as scrolling a feed while going back and forth between list and detail, rather than decoding one photo in isolation.

A useful before-and-after record includes the device or emulator configuration, input set, route through the app, and the point where you inspect the peak. For example, load several camera images, open one detail view, return to the list, and repeat with another image before the first requested detail would normally finish. Compare the same sequence with identical files and destinations. If the retained memory continues to climb after each return, look for duplicate ownership or stale work. If memory briefly spikes only when switching images, inspect the overlap between the decode and transform. These symptoms call for different fixes.

When a measured peak is unacceptable, first check whether the reported bitmap dimensions match the requested display size. A mismatch points back to the request or the loader. When the dimensions already look reasonable, examine how many buffers exist at the same time. Reducing the sample quality another step can hide a lifetime problem at the cost of a blurrier preview.

If an 800 × 600 preview gets its required detail from a 1000 × 750 decode, make that the normal path. Save full-resolution work for a feature that actually needs it, and verify the peak when users move between both.

You Might Also Like

View all articles
Android Memory Optimization for Low RAM Devices
8 min read

Android Memory Optimization for Low RAM Devices

A practical guide to keeping Android apps responsive on memory-constrained devices by measuring the working set, controlling bitmaps, releasing caches, and testing real process pressure.