Fix Image.getSize failing for data: URIs on Android (#58353)

Summary:
Pull Request resolved: https://github.com/react/react-native/pull/58353

Fixes https://github.com/react/react-native/issues/57787.
Supersedes https://github.com/react/react-native/pull/57788.

## Context
On Android, `Image.getSize()` and `Image.getSizeWithHeaders()` reject for every `data:` URI.
Both resolve dimensions through Fresco's encoded-image pipeline. That pipeline has producer
sequences only for network, local-file and local-content URIs; every other scheme falls through to
a throw:
    Unsupported uri scheme for encoded image fetch! Uri is: data:image/jpg;base64,...
Fresco's decoded-image pipeline does handle the scheme (`SOURCE_TYPE_DATA -> dataFetchSequence`), so
the capability exists — the encoded entry point simply does not expose it. A previous change added a
fast path for `res://` URIs for exactly this reason; `data:` was never given one.
Any app that gates rendering on `getSize` therefore cannot display an inline base64 image on
Android at all, while iOS is unaffected.
## This Diff
- Adds a `data:` fast path to `getSize` and `getSizeWithHeaders`, mirroring the existing
  resource-drawable fast path, routed through `fetchDecodedImage` rather than `fetchEncodedImage`.
- Pins the request to auto-rotate so it produces the same Fresco bitmap cache key that
  `ReactImageView` builds for the same URI. Rotation options are part of that key, so a mismatch
  here would decode into a key nothing reads and force a second decode at render time.
- Sets `DownsampleMode.NEVER` so the reported dimensions stay intrinsic rather than
  post-downsample, preserving the behaviour the encoded path was originally adopted for. That
  option is absent from the bitmap cache key, so it does not disturb the parity above.
- Reads the visible dimensions straight off the decoded image, which has already had its EXIF
  rotation applied, rather than repeating the axis swap the encoded subscriber performs by hand.
  `BaseCloseableStaticBitmap` applies that same predicate internally, so repeating it here would
  double-apply it.
- Adds unit coverage for the `data:` scheme, which had none: decoded-pipeline routing, cache-key
  parity with `ReactImageView`, intrinsic dimensions, the headers variant, and both failure paths.
- Adds two `data:` rows to the RNTester `Image.getSize` platform test — one plain, one tagged EXIF
  orientation 6 — so a real decode, rather than a mocked pipeline, proves the reported dimensions
  are the visible ones. Both are inline base64, so they need no network.
Because the decode now warms the bitmap memory cache under the key the `<Image>` subsequently
reads, a caller that sets its image source from the `getSize` success callback paints from cache
instead of decoding at render time.
## Alternatives Considered
**Parse the dimensions out of the base64 header.** Satisfies the `getSize` contract and is cheaper,
but warms nothing. Callers that relied on the decode side effect for smooth playback would keep
re-decoding every frame at render time — it fixes the rejection without fixing the regression that
accompanied it.
**Add a `data:` arm to Fresco's encoded producer sequence.** Pushes a behavioural change into shared
image infrastructure used by every app, to serve a caller that wants a decoded result anyway. The
narrower fix belongs on this side.
**Have callers stop gating rendering on `getSize`.** Makes the image appear, but permanently
discards the decode-then-render ordering, leaving the surface visibly flickering.
Changelog:
[Android][Fixed] - Fix `Image.getSize()` and `Image.getSizeWithHeaders()` rejecting `data:` URIs

Reviewed By: Abbondanzo, javache, cortinico

Differential Revision: D118657320

fbshipit-source-id: 576ce8458c921b199d717161c2113a7d4f99221b
This commit is contained in:
Cole Huntley authored and meta-codesync[bot] committed 2026-09-04 20:56:05 -07:00
1 parent 08c7781e5a
commit 8cfde6d083
3 files changed
+275 -2

No files matched your search

@@ -13,13 +13,16 @@ import android.util.SparseArray
import com.facebook.common.executors.CallerThreadExecutor
import com.facebook.common.memory.PooledByteBuffer
import com.facebook.common.references.CloseableReference
import com.facebook.common.util.UriUtil
import com.facebook.datasource.BaseDataSubscriber
import com.facebook.datasource.DataSource
import com.facebook.datasource.DataSubscriber
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.fbreact.specs.NativeImageLoaderAndroidSpec
import com.facebook.imagepipeline.common.RotationOptions
import com.facebook.imagepipeline.core.DownsampleMode
import com.facebook.imagepipeline.core.ImagePipeline
import com.facebook.imagepipeline.image.CloseableImage
import com.facebook.imagepipeline.image.EncodedImage
import com.facebook.imagepipeline.request.ImageRequest
import com.facebook.imagepipeline.request.ImageRequestBuilder
@@ -93,6 +96,11 @@ internal class ImageLoaderModule : NativeImageLoaderAndroidSpec, LifecycleEventL
resolveResourceSize(uriString, promise)
return
}
// Fast path: data: URIs are served by the decoded pipeline; see resolveDataUriSize.
if (UriUtil.isDataUri(source.uri)) {
resolveDataUriSize(source.uri, promise)
return
}
val request: ImageRequest =
ImageRequestBuilder.newBuilderWithSource(source.uri)
.setRotationOptions(RotationOptions.disableRotation())
@@ -122,6 +130,11 @@ internal class ImageLoaderModule : NativeImageLoaderAndroidSpec, LifecycleEventL
resolveResourceSize(uriString, promise)
return
}
// Fast path: a data: URI carries its own bytes, so headers are not applicable.
if (UriUtil.isDataUri(source.uri)) {
resolveDataUriSize(source.uri, promise)
return
}
val imageRequestBuilder: ImageRequestBuilder =
ImageRequestBuilder.newBuilderWithSource(source.uri)
.setRotationOptions(RotationOptions.disableRotation())
@@ -180,6 +193,67 @@ internal class ImageLoaderModule : NativeImageLoaderAndroidSpec, LifecycleEventL
}
}
/**
* Resolve the intrinsic size of a `data:` URI: Fresco's encoded-image pipeline has no producer
* sequence for the scheme and throws, while its decoded pipeline has one.
*
* Both request options are load-bearing. `autoRotate` matches
* [com.facebook.react.views.image.ReactImageView], so the decode warms the bitmap cache under the
* key that view later reads — `disableRotation` would warm a dead one. `DownsampleMode.NEVER`
* keeps the reported size intrinsic, at the cost of caching a larger bitmap than that view alone
* would decode above `maxBitmapDimension`.
*/
private fun resolveDataUriSize(uri: Uri, promise: Promise) {
val request =
ImageRequestBuilder.newBuilderWithSource(uri)
.setRotationOptions(RotationOptions.autoRotate())
.setDownsampleOverride(DownsampleMode.NEVER)
.build()
val dataSource = imagePipeline.fetchDecodedImage(request, callerContext)
dataSource.subscribe(createDecodedSizeSubscriber(promise), CallerThreadExecutor.getInstance())
}
private fun createDecodedSizeSubscriber(
promise: Promise,
): DataSubscriber<CloseableReference<CloseableImage>> =
object : BaseDataSubscriber<CloseableReference<CloseableImage>>() {
override fun onNewResultImpl(dataSource: DataSource<CloseableReference<CloseableImage>>) {
if (!dataSource.isFinished) {
return
}
val ref = dataSource.result
if (ref == null) {
promise.reject(ERROR_GET_SIZE_FAILURE, "Failed to get the size of the image")
return
}
try {
// Already the visible dimensions: the decode applied the EXIF rotation, which is why
// this does not repeat the axis swap the encoded subscriber has to do by hand.
val image = ref.get()
val width = image.width
val height = image.height
if (width < 0 || height < 0) {
promise.reject(ERROR_GET_SIZE_FAILURE, "Failed to get the size of the image")
return
}
promise.resolve(
buildReadableMap {
put("width", width)
put("height", height)
},
)
} catch (e: Exception) {
promise.reject(ERROR_GET_SIZE_FAILURE, e)
} finally {
CloseableReference.closeSafely(ref)
}
}
override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>) {
promise.reject(ERROR_GET_SIZE_FAILURE, dataSource.failureCause)
}
}
/**
* Resolve the intrinsic size of a drawable resource by name. Works for all drawable types
* including VectorDrawable, which cannot be decoded by Fresco's encoded-image pipeline.
@@ -9,10 +9,23 @@ package com.facebook.react.modules.image
import android.content.res.Resources
import android.graphics.drawable.Drawable
import androidx.core.net.toUri
import com.facebook.common.references.CloseableReference
import com.facebook.datasource.DataSource
import com.facebook.datasource.DataSubscriber
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory
import com.facebook.imagepipeline.common.RotationOptions
import com.facebook.imagepipeline.core.DownsampleMode
import com.facebook.imagepipeline.core.ImagePipeline
import com.facebook.imagepipeline.image.CloseableImage
import com.facebook.imagepipeline.request.ImageRequest
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactTestHelper
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
import com.facebook.react.views.image.ReactCallerContextFactory
import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper
import com.facebook.testutils.shadows.ShadowArguments
import com.facebook.testutils.shadows.ShadowSoLoader
@@ -24,22 +37,30 @@ import org.junit.runner.RunWith
import org.mockito.MockedStatic
import org.mockito.Mockito.mockStatic
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** The payload is never decoded — every test here mocks the image pipeline. */
private const val DATA_URI = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA=="
@Config(shadows = [ShadowArguments::class, ShadowSoLoader::class])
@RunWith(RobolectricTestRunner::class)
class ImageLoaderModuleTest {
private lateinit var imageLoaderModule: ImageLoaderModule
private lateinit var mockedHelper: MockedStatic<ResourceDrawableIdHelper>
private lateinit var reactContext: ReactApplicationContext
@Before
fun setUp() {
val reactContext = ReactTestHelper.createCatalystContextForTest()
reactContext = ReactTestHelper.createCatalystContextForTest()
imageLoaderModule = ImageLoaderModule(reactContext)
mockedHelper = mockStatic(ResourceDrawableIdHelper::class.java)
@@ -197,6 +218,154 @@ class ImageLoaderModuleTest {
assertThat(promise.errorCode).isEqualTo("E_INVALID_URI")
}
@Test
fun testGetSizeWithDataUriUsesDecodedPipeline() {
val pipeline = mock<ImagePipeline>()
val dataSource = finishedDataSource(decodedRef(1408, 1408))
whenever(pipeline.fetchDecodedImage(anyOrNull(), anyOrNull())).thenReturn(dataSource)
val promise = SimplePromise()
moduleWithPipeline(pipeline).getSize(DATA_URI, promise)
captureSubscriber(dataSource).onNewResult(dataSource)
// The encoded pipeline has no producer sequence for data: URIs and throws for them, so routing
// there at all is the regression this guards.
verify(pipeline, never()).fetchEncodedImage(any(), anyOrNull())
assertThat(promise.rejected).isEqualTo(0)
assertThat(promise.resolved).isEqualTo(1)
val result = promise.value as ReadableMap
assertThat(result.getInt("width")).isEqualTo(1408)
assertThat(result.getInt("height")).isEqualTo(1408)
}
@Test
fun testGetSizeWithHeadersWithDataUriUsesDecodedPipeline() {
val pipeline = mock<ImagePipeline>()
val dataSource = finishedDataSource(decodedRef(640, 480))
whenever(pipeline.fetchDecodedImage(anyOrNull(), anyOrNull())).thenReturn(dataSource)
val promise = SimplePromise()
moduleWithPipeline(pipeline).getSizeWithHeaders(DATA_URI, null, promise)
captureSubscriber(dataSource).onNewResult(dataSource)
verify(pipeline, never()).fetchEncodedImage(any(), anyOrNull())
assertThat(promise.rejected).isEqualTo(0)
val result = promise.value as ReadableMap
assertThat(result.getInt("width")).isEqualTo(640)
assertThat(result.getInt("height")).isEqualTo(480)
}
/**
* The decode is only worth doing if it lands under the key `ReactImageView` later reads. Rotation
* options are part of the bitmap cache key, so `disableRotation` here would warm a key nothing
* looks up and every rendered frame would decode a second time.
*/
@Test
fun testGetSizeWithDataUriSharesBitmapCacheKeyWithReactImageView() {
val pipeline = mock<ImagePipeline>()
val dataSource = finishedDataSource(decodedRef(1408, 1408))
whenever(pipeline.fetchDecodedImage(anyOrNull(), anyOrNull())).thenReturn(dataSource)
val promise = SimplePromise()
moduleWithPipeline(pipeline).getSize(DATA_URI, promise)
val requestCaptor = argumentCaptor<ImageRequest>()
verify(pipeline).fetchDecodedImage(requestCaptor.capture(), anyOrNull())
// Mirrors ReactImageView.maybeUpdateViewFromRequest for a data: URI: shouldResize() is false
// for a non-file, non-content URI under the default resize method, so resize options are null.
// ReactImageView spells the rotation as the deprecated setAutoRotateEnabled(true), which
// delegates to exactly this, so the request it builds — and its cache key — is unchanged.
val reactImageViewRequest =
ImageRequestBuilder.newBuilderWithSource(DATA_URI.toUri())
.setRotationOptions(RotationOptions.autoRotate())
.setProgressiveRenderingEnabled(false)
.build()
val cacheKeyFactory = DefaultCacheKeyFactory.getInstance()
assertThat(cacheKeyFactory.getBitmapCacheKey(requestCaptor.firstValue, null))
.isEqualTo(cacheKeyFactory.getBitmapCacheKey(reactImageViewRequest, null))
}
/**
* Guards the intent of the change that moved getSize off the decoded pipeline in the first place:
* the reported dimensions must be intrinsic, not post-downsample.
*/
@Test
fun testGetSizeWithDataUriRequestsAnUndownsampledDecode() {
val pipeline = mock<ImagePipeline>()
val dataSource = finishedDataSource(decodedRef(1408, 1408))
whenever(pipeline.fetchDecodedImage(anyOrNull(), anyOrNull())).thenReturn(dataSource)
moduleWithPipeline(pipeline).getSize(DATA_URI, SimplePromise())
val requestCaptor = argumentCaptor<ImageRequest>()
verify(pipeline).fetchDecodedImage(requestCaptor.capture(), anyOrNull())
val request = requestCaptor.firstValue
assertThat(request.downsampleOverride).isEqualTo(DownsampleMode.NEVER)
assertThat(request.resizeOptions).isNull()
assertThat(request.rotationOptions).isEqualTo(RotationOptions.autoRotate())
}
@Test
fun testGetSizeWithDataUriRejectsWhenDecodeFails() {
val pipeline = mock<ImagePipeline>()
val dataSource = mock<DataSource<CloseableReference<CloseableImage>>>()
whenever(dataSource.failureCause).thenReturn(RuntimeException("decode failed"))
whenever(pipeline.fetchDecodedImage(anyOrNull(), anyOrNull())).thenReturn(dataSource)
val promise = SimplePromise()
moduleWithPipeline(pipeline).getSize(DATA_URI, promise)
captureSubscriber(dataSource).onFailure(dataSource)
assertThat(promise.resolved).isEqualTo(0)
assertThat(promise.rejected).isEqualTo(1)
assertThat(promise.errorCode).isEqualTo("E_GET_SIZE_FAILURE")
assertThat(promise.errorMessage).contains("decode failed")
}
@Test
fun testGetSizeWithDataUriRejectsWhenDecodeYieldsNoResult() {
val pipeline = mock<ImagePipeline>()
val dataSource = finishedDataSource(null)
whenever(pipeline.fetchDecodedImage(anyOrNull(), anyOrNull())).thenReturn(dataSource)
val promise = SimplePromise()
moduleWithPipeline(pipeline).getSize(DATA_URI, promise)
captureSubscriber(dataSource).onNewResult(dataSource)
assertThat(promise.resolved).isEqualTo(0)
assertThat(promise.rejected).isEqualTo(1)
assertThat(promise.errorCode).isEqualTo("E_GET_SIZE_FAILURE")
}
private fun moduleWithPipeline(pipeline: ImagePipeline): ImageLoaderModule =
ImageLoaderModule(reactContext, pipeline, mock<ReactCallerContextFactory>())
private fun decodedRef(width: Int, height: Int): CloseableReference<CloseableImage> {
val image = mock<CloseableImage>()
whenever(image.width).thenReturn(width)
whenever(image.height).thenReturn(height)
return CloseableReference.of(image)
}
private fun finishedDataSource(
result: CloseableReference<CloseableImage>?,
): DataSource<CloseableReference<CloseableImage>> {
val dataSource = mock<DataSource<CloseableReference<CloseableImage>>>()
whenever(dataSource.isFinished).thenReturn(true)
whenever(dataSource.result).thenReturn(result)
return dataSource
}
private fun captureSubscriber(
dataSource: DataSource<CloseableReference<CloseableImage>>,
): DataSubscriber<CloseableReference<CloseableImage>> {
val captor = argumentCaptor<DataSubscriber<CloseableReference<CloseableImage>>>()
verify(dataSource).subscribe(captor.capture(), any())
return captor.firstValue
}
internal class SimplePromise : Promise {
companion object {
private const val ERROR_DEFAULT_CODE = "EUNSPECIFIED"
@@ -809,6 +809,22 @@ const smallImage = {
uri: IMAGE1,
};
// 16x8 JPEG with no EXIF orientation, inline so the check needs no network.
const GET_SIZE_JPEG_DATA_URI =
'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABQODxIPDRQSEBIXFRQYHjIhHhwcHj0sLiQySUBMS0dARkVQWnNiU' +
'FVtVkVGZIhlbXd7gYKBTmCNl4x9lnN+gXz/2wBDARUXFx4aHjshITt8U0ZTfHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8f' +
'Hx8fHx8fHx8fHx8fHz/wAARCAAIABADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAT/xAAWEAEBAQAAAAAAAAAAAAAAAAAAFWL/x' +
'AAVAQEBAAAAAAAAAAAAAAAAAAAFBv/EABcRAAMBAAAAAAAAAAAAAAAAAAADFFH/2gAMAwEAAhEDEQA/AKYuSLkExQzRSpun/9k=';
// The same 16x8 raster tagged EXIF orientation 6 (rotate 90 CW to display), so a
// decoder that honours the tag reports 8x16 and one that ignores it reports 16x8.
const GET_SIZE_EXIF_ROTATED_JPEG_DATA_URI =
'data:image/jpeg;base64,/9j/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAABgAAAAAAAAD/4AAQSkZJRgABAQAAAQABAAD/2wBDABQOD' +
'xIPDRQSEBIXFRQYHjIhHhwcHj0sLiQySUBMS0dARkVQWnNiUFVtVkVGZIhlbXd7gYKBTmCNl4x9lnN+gXz/2wBDARUXFx4aHjshITt8U0ZTf' +
'Hx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHz/wAARCAAIABADASIAAhEBAxEB/8QAFQABAQAAAAAAA' +
'AAAAAAAAAAAAAT/xAAWEAEBAQAAAAAAAAAAAAAAAAAAFWL/xAAVAQEBAAAAAAAAAAAAAAAAAAAFBv/EABcRAAMBAAAAAAAAAAAAAAAAAAADF' +
'FH/2gAMAwEAAhEDEQA/AJYuSLkDVDNJqpun/9k=';
const GET_SIZE_TEST_IMAGES: ReadonlyArray<{
expectedHeight: number,
expectedWidth: number,
@@ -834,6 +850,20 @@ const GET_SIZE_TEST_IMAGES: ReadonlyArray<{
uri: 'https://www.facebook.com/assets/react_native_oss_tests/exif-6@1x.jpg',
name: 'EXIF rotated JPEG',
},
{
expectedHeight: 8,
expectedWidth: 16,
uri: GET_SIZE_JPEG_DATA_URI,
name: 'data: URI JPEG',
},
{
// Transposed against the row above: the tag must be applied, so these are
// the visible dimensions rather than the 16x8 stored raster.
expectedHeight: 16,
expectedWidth: 8,
uri: GET_SIZE_EXIF_ROTATED_JPEG_DATA_URI,
name: 'EXIF rotated data: URI JPEG',
},
];
function getImageSize(uri: string): Promise<{height: number, width: number}> {
@@ -897,7 +927,7 @@ function ImageGetSizePlatformTest(props: PlatformTestComponentBaseProps) {
return (
<RNTesterText>
Calling Image.getSize for {GET_SIZE_TEST_IMAGES.length} remote images.
Calling Image.getSize for {GET_SIZE_TEST_IMAGES.length} images.
</RNTesterText>
);
}