diff --git a/.changeset/web-uri-include-base64.md b/.changeset/web-uri-include-base64.md new file mode 100644 index 0000000..e2d71ba --- /dev/null +++ b/.changeset/web-uri-include-base64.md @@ -0,0 +1,11 @@ +--- +'@react-native-community/image-editor': minor +--- + +fix(web): `result.uri` is now a data URI, and `includeBase64` is honored + +On web, `result.uri` returned the bare base64 payload, so `` rendered nothing — the documented behavior (and what iOS/Android return) is a URI. It is now a `data:` URI, and the bare payload stays on `result.base64`. + +`includeBase64` was never read on web: `result.base64` was always present, and reading it (or spreading the result, or `JSON.stringify`, or inspecting it in DevTools) triggered a full `canvas.toDataURL()` that was never asked for. `base64` is now defined only when `includeBase64` is true, matching native, and the data URI is computed once and shared between `uri` and `base64`. + +If you relied on the old web `result.uri` being the base64 payload, use `result.base64` (with `includeBase64: true`). diff --git a/src/index.web.ts b/src/index.web.ts index aba5ad9..4aa8086 100644 --- a/src/index.web.ts +++ b/src/index.web.ts @@ -99,7 +99,17 @@ class ImageEditor { throw new Error('Image cannot be created from canvas'); } - let _path: string, _uri: string; + let _path: string; + let _dataUri: string | undefined; + + // `canvas.toDataURL()` is expensive, so build the data URI only + // when `uri` or `base64` is actually read. + function getDataUri() { + if (_dataUri === undefined) { + _dataUri = canvas.toDataURL(type, quality); + } + return _dataUri; + } const result: CropResult = { width: canvas.width, @@ -114,18 +124,26 @@ class ImageEditor { } return _path; }, + // Unlike iOS/Android, the web has no file to point at, so `uri` + // is the data URI (see README) — usable directly as an `Image` + // `source`. `base64` stays the bare payload, as on the other + // platforms. get uri() { - return result.base64 as string; - }, - get base64() { - if (!_uri) { - _uri = canvas.toDataURL(type, quality); - } - return _uri.split(',')[1]; - // ^^^ remove `data:image/xxx;base64,` prefix (to align with iOS/Android platform behavior) + return getDataUri(); }, }; + if (cropData.includeBase64) { + Object.defineProperty(result, 'base64', { + get() { + // strip the `data:image/xxx;base64,` prefix (to align with + // iOS/Android platform behavior) + return getDataUri().split(',')[1] ?? ''; + }, + enumerable: true, + }); + } + return result; }); }