Skip to content

fix(ios): reject invalid quality before downloading; document why the full-res decode is deliberate - #222

Merged
retyui merged 2 commits into
masterfrom
fix/ios-downsampling-validation
Dec 2, 2026
Merged

retyui merged 2 commits into
masterfrom
fix/ios-downsampling-validation

Conversation

@retyui

@retyui retyui commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Two iOS findings. One is fixed; the other is not, and the review that produced it was wrong about the fix. Read the H10 section before reviewing anything else.

H12 (b3e3140) — fixed: invalid quality discovered only after download + decode

cropImage(remoteUrl, { quality: 5 }) downloaded and fully decoded the source image before rejecting. The range check now runs immediately after adaptParamsWithFormat:, before the NSMutableURLRequest is built and before loadImageWithURLRequest:. The old in-callback check is removed, so this is a pure move, not a duplicate.

Error code (RCTErrorUnspecified) and message string ("quality must be a number between 0 and 1") are byte-identical, so apps matching on them are unaffected. params is captured by value in both positions — no lifetime change.

Safety of an early return verified against RN source: RCTTurboModule.mm:404 (invokeCopy(resolveBlock, rejectBlock)) invokes the method synchronously inside the Promise constructor executor, so an early reject settles the promise exactly once with both blocks live. Every path settles exactly once: early quality reject, loader error reject, writeError reject, final resolve.

Deliberately NOT changed: format

format: 'webp' still silently produces JPEG rather than erroring. There is no late error to hoist — per src/NativeRNCImageEditor.ts:50, a format other than png/jpeg means "default auto-detection based on given image", and webp is a documented public value (src/types.ts:10, CropResult.type includes 'image/webp'). So it isn't an invalid value; turning it into a rejection is a new behavior change that breaks existing iOS callers while Android still writes webp. That fallback — and its real bug, that iOS detects format from the URL path extension only, so extension-less/data:/ph:// URLs always land on JPEG — is a separate finding, left for its own PR.

offset/size likewise got no hoisted check: both are required by codegen, so there's no optional to test for presence (which is all Android's up-front check does), and a bounds check structurally cannot run before the download since it needs decoded dimensions.

H10 — NOT fixed. The memory bug is real; the proposed fix is wrong

The diagnosis stands and is confirmed: the 2-arg loadImageWithURLRequest: passes size:CGSizeZero, scale:1 (now verified verbatim at RCTImageLoader.mm:361-374), which reaches RCTDecodeImageWithData where a zero destSize becomes sourceSize → createThumbnail false → full-resolution CGImageSourceCreateImageAtIndex. A 100×100 crop of a 12 MP photo decodes the whole image.

But downsampling before the crop is not safe here, and I could not make it correct. I picked the "reachable" route the review suggested, verified it end-to-end, and hit four blockers:

  1. Sizing from size is catastrophic, not merely lossy. offset/size are in source pixels. A 100×100 crop of a 4000×3000 source gives RCTTargetSize(cover) → 133×100, so kCGImageSourceThumbnailMaxPixelSize = 133 — the source shrinks ~30× before the crop. The crop region collapses from 100×100 source px to ~3×3 px, which RCTTransformImage then upsamples back to 100×100. A pixel-exact crop becomes blurred mush. The root problem: in RCTTransformImage(image, targetSize, …) the source region and the output size are the same value, so you cannot downsample to size and still crop at size.
  2. Sizing from displaySize (what Android does) needs the source pixel dimensions, which iOS doesn't have. The decode returns [UIImage imageWithCGImage:imageRef scale:destScale …], so .size is downsampled points at an arbitrary scale and the source dims are unrecoverable. Recovering them means either a second metadata fetch (getImageSizeForURLRequest: — near-free for local file://, a full re-download for remote) or bypassing RCTImageLoader and losing its caching, ph:// support and header handling. Getting the ratio wrong is a silent wrong crop.
  3. Orientation semantics would change for EXIF-rotated JPEGs. The thumbnail path bakes the transform and returns UIImageOrientationUp (RCTImageUtils.mm:326-336, confirmed: kCGImageSourceCreateThumbnailWithTransform: @YES with a comment saying exactly that); the full-res path returns an orientation-tagged UIImage. The crop math reads image.size, so switching branches silently changes crop geometry for the common camera-JPEG case.
  4. clipped:YES would additionally apply RCTResizeImageIfNeeded to the decoded image before the crop — another resample to neutralize via clipped:NO.

The minimal correct subset (downsample to displaySize, source dims via a metadata pass) is a rewrite of the load path with a network round-trip on remote URLs — not a minimal diff, and untestable in this environment. Reachability of a selector is not reachability of a correct fix.

So this PR ships the corrected documentation only:

  • :79-82 — the doc comment claimed displaySize "is an optimization - if specified, the image will be scaled down to displaySize rather than size". Both halves are false: it isn't an optimization, and it scales to displaySize in addition to size, not rather than it.
  • :132-139 — a comment at the load site recording that the full-resolution decode is deliberate and why, so the next reader doesn't spend an afternoon rediscovering this.

displaySize does not reduce peak decode memory today. That remains an open bug. Also worth knowing: Android's non-resize path uses BitmapRegionDecoder, a genuine region decode with no full-image decode at all. ImageIO has no equivalent, so on that path iOS can only approach Android, never match it. Any real H10 fix should be its own PR with a plan to get source dimensions without a re-download, plus device measurements.

Verification status

Not compiled — no Pods install, no simulator. Unverified: compilation, crop output, and all memory figures (the ~49 MB number is the review's estimate, not a measurement; the H10 improvement here is zero, since behavior is unchanged).

Verified by reading the pinned RN 0.87.1 in node_modules: the RCTImageLoader selectors exist; CGSizeZero/scale:1 defaults; the thumbnail transform-bake; the RCTIsMainQueue() offload at RCTImageLoader.mm:969-981; RCTTurboModule.mm:404 synchronous invocation. No new ARC captures or retain cycles (H12 adds no block; H10 is comments only). No CGFloat/points-vs-pixels logic touched. Each commit is self-consistent standalone — the quality check is present in both, so reverting H12 alone leaves it in the callback.

Left for other PRs (from the same review)

  • H10 downsampling — needs the source-dimension plan above
  • M1 format auto-detection (iOS detects from URL extension only)
  • M3 out-of-bounds crop behavior (needs decoded dims)
  • M2 displaySize width-xor-height skip at :153 (&& against DEFAULT_DISPLAY_SIZE 0)

The doc comment claimed displaySize was an optimization that scaled the
image down "rather than size". It is neither: displaySize is applied by a
second RCTTransformImage pass after the full-resolution decode, so the
source is always decoded at full resolution regardless.

Add a note at the loadImageWithURLRequest: call site recording why the
decode is deliberately full-resolution, so the next reader doesn't assume
the sized loader overload is a one-line fix. offset/size are in source
pixels and ImageIO can only downsample the whole image, so downsampling
before the crop shrinks the crop region itself. Android only downsamples
this way in cropAndResizeTask, where it rescales offset/size into
downsampled space using the source pixel dimensions - which the loaded
UIImage does not expose.

Behaviour is unchanged; this is documentation only. The memory issue is
real and left unfixed.
`quality` was checked inside the image loader callback, so
cropImage(remoteUrl, {quality: 5}) transferred and decoded the whole
source image before rejecting. The value is only used by
UIImageJPEGRepresentation at the end, so nothing about it depends on the
decoded image: move the check above loadImageWithURLRequest: so it fails
immediately, as Android already does.

The error code and message are unchanged, so callers that match on them
keep working.

`format`, `offset` and `size` are left alone deliberately:

- `format` has no late error to hoist. Anything other than png/jpeg is
  documented as "auto-detect from the URL" and webp is in the public
  type, so it is not an invalid value - it silently falls back, and that
  is existing behaviour callers may rely on. Turning it into a rejection
  would break iOS callers while Android happily writes webp.
- `offset`/`size` are required by codegen, and checking them against the
  decoded dimensions can only happen after the image is loaded.
@retyui
retyui marked this pull request as ready for review December 2, 2026 19:06
@retyui
retyui merged commit 6f4fdea into master Dec 2, 2026
11 checks passed
@retyui
retyui deleted the fix/ios-downsampling-validation branch December 2, 2026 19:06
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