Skip to content

fix(android): decode the crop region, not the whole image, when resizing - #225

Draft
retyui wants to merge 1 commit into
masterfrom
fix/android-decode-crop-region
Draft

retyui wants to merge 1 commit into
masterfrom
fix/android-decode-crop-region

Conversation

@retyui

@retyui retyui commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

K2: OOM. Decode only the crop region instead of the whole image. inSampleSize now comes from the actual decoded bitmap. Intermediate bitmaps are recycled, and decoder.recycle() now runs in a finally.

When displaySize was set, inSampleSize was computed from the crop rect, but the decode used Rect(0, 0, decoder.width, decoder.height), which is the whole image. Example: a 200×200 crop with displaySize: 100 on a 10000×7500 panorama picked inSampleSize=2 and decoded ~75 MB to make a 100×100 thumbnail (ideal ≈160 KB). So passing displaySize made memory use worse than leaving it out.

inSampleSize is now derived from the region that was actually decoded. That also fixes itself on API 21–23, where decodeRegion ignores inSampleSize, so no Build.VERSION branch is needed.

No out-of-bounds clamping was added on purpose. decodeRegion already throws IOException for that case, and clamping silently would turn a rejection into different output.

Note: without K1 (#224), an OutOfMemoryError still escapes catch (Exception).

Verification

Not compiled. No :android:compileDebugKotlin run and nothing run on a device. The Kotlin was checked for syntax errors only, and the external API signatures were checked against the published artifacts.

Split out of #221 (now closed), which bundled six Android fixes in ImageEditorModuleImpl.kt. Each one can be reviewed and merged separately.

With `displaySize`, `inSampleSize` was computed from the crop rect but the
decode asked for `Rect(0, 0, decoder.width, decoder.height)` — the entire
source image. So a small crop of a huge photo picked a small sample size
and allocated a full-resolution bitmap: a 10000x7500 panorama cropped to
200x200 with `displaySize {100, 100}` decoded to 5000x3750 ARGB_8888,
about 75 MB, to produce a 100x100 thumbnail. Passing `displaySize` made
memory strictly worse than omitting it, and the intermediate bitmap was
never recycled. `cropTask` already decoded just the crop rect.

Decode the orientation-mapped crop rect instead and size `inSampleSize`
from the region actually decoded. Take the downsample factor from the
decoded bitmap rather than assuming `inSampleSize` was honoured, since
`decodeRegion` ignores it on API 21-23 (minSdk is 21), and recycle the
decoded bitmap once it has been scaled (unless `createBitmap` returned
that same instance). Also recycle the decoder, which this path never
released.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant