# Bitmap Fundamentals: Pixel Buffers, Byte Layout, and Why File Size Lies About Memory

> A bitmap's memory footprint is pure arithmetic, width times height times bytes-per-pixel, and it has nothing to do with the compressed file size that produced it.

**Date:** 2026-10-16T00:00:00.000Z
**Tags:** Canvas, Graphics, Memory

## The intuition

A file's size on disk and a decoded bitmap's size in memory feel like the
same number, just scaled. They aren't related at all.

* A decoded bitmap is a flat grid of pixels sitting in RAM, with no memory
  of whatever compression produced it.
* Its memory cost is pure arithmetic: `width × height × bytes-per-pixel`.
  Nothing about the original file enters that formula.
* That's why a tiny JPEG straight off a phone camera can blow up into tens
  of megabytes once decoded, while a huge file can decode into almost
  nothing.

## Same pixels, different byte count

The part of the formula you actually control is bytes-per-pixel, via
`Bitmap.Config`. Same image, same dimensions, different config:

```kotlin
val width = 4000
val height = 3000

// ARGB_8888: 4 bytes/pixel, stored in memory as R, G, B, A (the name
// describes the int-packing order, not the raw byte order)
val full = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
full.byteCount // 4000 * 3000 * 4 = 48,000,000 bytes ≈ 46 MB

// RGB_565: 2 bytes/pixel, no alpha channel at all
val half = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
half.byteCount // 4000 * 3000 * 2 = 24,000,000 bytes ≈ 23 MB
```

Same pixel grid, same dimensions, half the memory, because the thing that
changed is bytes-per-pixel, not pixel count. Each pixel is a fixed-size
group of bytes, stored row by row in one flat block of memory:

```mermaid caption="ARGB_8888: four bytes encode one pixel, in memory order" figureNumber={1}
flowchart LR
    P[One pixel] --> R[Byte 0: Red]
    P --> G[Byte 1: Green]
    P --> B[Byte 2: Blue]
    P --> A[Byte 3: Alpha]
```

## File size and decoded memory are unrelated numbers

A file's compressed size and that same image's decoded memory cost come
from two different stages of the pipeline, and they don't scale together.

```mermaid caption="Decode breaks the link between file size and memory" figureNumber={2}
flowchart LR
    A[File on disk: compressed bytes] -->|decode| B[Raw pixel buffer in RAM]
    B --> C[memory = width × height × bytes-per-pixel]
```

* **File size** depends on content. A photo of noise compresses badly, a
  blank sky compresses to almost nothing, and neither has a fixed
  relationship to pixel dimensions.
* **Decoded memory** depends only on pixel dimensions and
  bytes-per-pixel. By the time you're holding a `Bitmap`, the compression
  is gone. It's just numbers in an array again.

If you've ever hit an `OutOfMemoryError` that made no sense given how
small the asset file was, this is why: a 20KB JPEG straight off a phone
camera can be 4000 × 3000 pixels, which decodes to 4000 × 3000 × 4 ≈ 46 MB
at `ARGB_8888`. The file was 20KB. The thing you're holding in RAM is
46MB. File size was never the number that mattered, pixel dimensions
were.

> **The fundamental**
>
> A bitmap is a **pixel buffer (A flat, row-major block of memory holding decoded pixels: every pixel occupies the same fixed number of bytes, in order, with no memory of whatever compression produced it.)**: a flat, row-major (Rows stored one after another in memory, left to right then top to bottom, rather than column by column.) block of memory where
> every pixel occupies the same fixed number of bytes. Total memory is
> deterministic, `width × height × bytes-per-pixel`, and it's entirely
> decoupled from the compressed file size that produced it.
>
> Bytes-per-pixel is a trade-off along two axes: how many channels you keep
> (alpha, RGB, or just luminance), and how many bits per channel (8, 5/6, or
> 16-bit float). Shrink either axis and the pixel buffer gets smaller. The
> picture's resolution hasn't changed at all.

## Elsewhere: same fundamental, different framework

* **iOS:** `CGImage`/`UIImage` backed by a `CGBitmapContext`, where you
  choose `bitsPerComponent` and a `CGColorSpace`. A grayscale colorspace
  with no alpha gives the same 1 byte/pixel as `ALPHA_8`.
* **Web/Canvas:** `ImageData` is always RGBA at 4 bytes/pixel, with no
  smaller native option. Getting a grayscale saving means packing a
  `Uint8ClampedArray` at 1 byte/pixel by hand and drawing it yourself.
* **PNG, on disk rather than in memory:** has explicit color types for the
  same idea: Truecolor+Alpha (4 bytes), Truecolor (3 bytes), Grayscale (1
  byte), Indexed/palette (1 byte plus a lookup table). Same channel-count
  trade-off, just persisted instead of live in RAM.
* **GPU textures (OpenGL/Vulkan):** formats like `RGBA8`, `RGB565`, and
  `R8` (a single red/luminance channel) mirror `Bitmap.Config` almost
  one-to-one. `R8` is the GPU-texture equivalent of `ALPHA_8` for
  grayscale.

## Where this actually trips people up

### Decoding at full resolution when you only need a thumbnail wastes the exact memory the intro warned about

`BitmapFactory.decodeFile()`/`decodeResource()` decode at the image's
native pixel dimensions by default, no matter how small the `ImageView`
that will display it is. Loading a 4000 × 3000 photo into a 120dp avatar
still allocates the full ~46MB `ARGB_8888` buffer, then throws most of it
away the moment the view scales it down.

Read the dimensions first, with zero pixel allocation, and pass a
computed `inSampleSize` to the real decode:

```kotlin
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(path, bounds) // outWidth/outHeight only, no pixel bytes allocated

var sampleSize = 1
while (bounds.outWidth / (sampleSize * 2) >= reqWidth &&
    bounds.outHeight / (sampleSize * 2) >= reqHeight) {
    sampleSize *= 2
}

val decoded = BitmapFactory.decodeFile(path, BitmapFactory.Options().apply {
    inSampleSize = sampleSize
})
```

`inSampleSize` divides both dimensions before decode, so memory drops
with the square of the factor: `inSampleSize = 4` turns a 46MB decode
into roughly 2.9MB. The formula from the intro, `width × height ×
bytes-per-pixel`, hasn't changed, it's just running against a smaller
width and height.

### A recycled bitmap crashes on the next read, not on the `recycle()` call

Image-loading libraries and custom caches can call `recycle()` on a
`Bitmap` to free its native memory immediately rather than waiting for
the GC. The crash doesn't happen there, it happens later, whenever
something still holding that reference calls `getPixels()` or draws it:
`IllegalStateException: Can't call getPixels() on a recycled bitmap`.

Check `bitmap.isRecycled()` before touching a `Bitmap` that outlived a
cache eviction or a config-change recreation, rather than wrapping every
pixel access in a try/catch after the fact.

### Reading raw pixels with the wrong row width skews the image diagonally

Platforms can pad each row to an alignment boundary for hardware
efficiency, so stride (The number of bytes one full row of a bitmap occupies in memory, including any padding. It can be larger than width times bytes-per-pixel.)
is sometimes larger than `width * bytesPerPixel`. `Bitmap.getRowBytes()`
returns the real value. Compute your own `width * bytesPerPixel` instead
and use it to walk a raw pixel buffer, and the image comes out
progressively skewed, because every row after the first is offset by
padding you never accounted for.

### A half-transparent red pixel isn't stored as `(255, 0, 0, 128)`

Android bitmaps store RGB values already multiplied by alpha, called
premultiplied alpha (Storing a pixel's color channels already scaled down by its own alpha value, instead of keeping color and transparency as independent numbers.).
Manually blend pixel bytes without accounting for this and semi-transparent
edges come out washed out or darkened, because you're scaling
already-scaled color values a second time.

### `getPixels()` throws on a `HARDWARE` bitmap

Since Android 8, `BitmapFactory` can decode straight into GPU memory for
fast display. That's great for memory, since the pixels never touch the
Java or native heap at all, but it also means you can't call
`getPixels()` or draw into it with a software `Canvas`. Code that assumes
every `Bitmap` is readable breaks the first time it hits one of these.

Every one of these gotchas, sizing the decode, picking a config, pooling
and recycling, is exactly what an image-loading library like Coil or
Glide automates. They don't bypass this arithmetic, they just compute it
for you behind a request builder.

**A bitmap's memory is `width × height × bytes-per-pixel`, period. Nothing
about the file that produced it, or the format it started in, changes
that arithmetic once it's decoded.**


---

Canonical page: https://recomposed.blog/bitmap-byte-layout-and-memory