TypeScript
fix(mobile): photo-library PNGs no longer fail after resizing (#26522)
shivam7632c3dc7039
diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.tsindex 546c28f408f..bdcd35c36ff 100644--- a/apps/mobile/src/lib/composerFiles.test.ts+++ b/apps/mobile/src/lib/composerFiles.test.ts@@ -124,28 +124,35 @@ describe("composer file attachments", () => {width: 4032,height: 3024,};+ type Size = { width: number; height: number };const native = {- size: { width: 1, height: 1 },- resizes: [] as Array<{ width?: number | null; height?: number | null }>,+ size: { width: 1, height: 1 } as Size,+ resizes: [] as Size[],saved: rendered as { uri: string; base64?: string },+ encode: null as ((size: Size, format: string) => { uri: string; base64?: string }) | null,};beforeEach(() => {native.size = { width: 1, height: 1 };native.resizes = [];native.saved = rendered;+ native.encode = null;mocks.manipulate.mockReset();mocks.release.mockReset();- mocks.manipulate.mockImplementation(() => {+ mocks.manipulate.mockImplementation((source: string | Size) => {+ let size = typeof source === "string" ? native.size : source;const context = {- resize(size: { width?: number | null; height?: number | null }) {- native.resizes.push(size);+ resize(next: Size) {+ native.resizes.push(next);+ size = next;return context;},renderAsync: async () => ({- ...native.size,+ width: size.width,+ height: size.height,release: mocks.release,- saveAsync: async () => native.saved,+ saveAsync: async (options: { format: string }) =>+ native.encode?.(size, options.format) ?? native.saved,}),};return context;@@ -210,6 +217,45 @@ describe("composer file attachments", () => {]);});+ it("shrinks a fitted PNG further when re-encoding it exceeds the image limit", async () => {+ const header = Buffer.alloc(24);+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(header);+ header.write("IHDR", 12);+ header.writeUInt32BE(1668, 16);+ header.writeUInt32BE(2388, 20);+ native.size = { width: 1668, height: 2388 };+ // Native PNG encoding of the 2000px resample is larger than the 7 MB original.+ native.encode = (size, format) => ({+ uri: `file:///cache/fitted-${size.width}x${size.height}.${format}`,+ base64: Buffer.alloc(size.width * size.height * 4).toString("base64"),+ });+ mocks.size.mockReturnValue(7 * 1024 * 1024);+ mocks.readBase64.mockResolvedValue(header.toString("base64"));+ mocks.pickMedia.mockResolvedValue({+ canceled: false,+ assets: [{ ...photo, fileName: "IMG_9280.png", mimeType: "image/png" }],+ });++ const result = await pickComposerImages({ existingCount: 0 });++ expect(result.error).toBeNull();+ const [image] = result.images;+ const last = native.resizes.at(-1)!;+ expect(native.resizes[0]).toEqual({ width: 1397, height: 2000 });+ expect(Math.max(last.width, last.height)).toBeLessThan(2000);+ expect(image).toEqual(+ expect.objectContaining({+ name: "IMG_9280.png",+ mimeType: "image/png",+ sizeBytes: last.width * last.height * 4,+ previewUri: `file:///cache/fitted-${last.width}x${last.height}.png`,+ }),+ );+ expect(image!.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES);+ expect(mocks.delete).toHaveBeenCalledWith("file:///cache/fitted-1397x2000.png");+ expect(mocks.delete).not.toHaveBeenCalledWith(image!.previewUri);+ });+it("measures the picker file instead of trusting the reported size", async () => {mocks.pickMedia.mockResolvedValue({canceled: false,diff --git a/apps/mobile/src/lib/composerImageFit.ts b/apps/mobile/src/lib/composerImageFit.tsindex fddeac277bc..18cd93b3fe7 100644--- a/apps/mobile/src/lib/composerImageFit.ts+++ b/apps/mobile/src/lib/composerImageFit.ts@@ -1,3 +1,4 @@+import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts";import {downscalableImageMimeType,fitImageAttachmentSize,@@ -6,8 +7,24 @@ import {IMAGE_DIMENSIONS_HEADER_BYTES,readImageDimensions,} from "@t3tools/shared/imageDimensions";+import { estimateBase64ByteSize } from "./base64";const PHOTO_JPEG_QUALITY = 0.85;+const MAX_BYTE_LIMIT_SHRINKS = 3;++function shrinkToByteLimit(+ size: { readonly width: number; readonly height: number },+ bytes: number,+): { width: number; height: number } | null {+ if (bytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) return null;+ // Encoded size tracks pixel count, so scale each edge by the square root with some headroom.+ const scale = Math.sqrt(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / bytes) * 0.9;+ const next = {+ width: Math.max(1, Math.floor(size.width * scale)),+ height: Math.max(1, Math.floor(size.height * scale)),+ };+ return next.width < size.width || next.height < size.height ? next : null;+}export async function renderPhoto(uri: string,@@ -16,21 +33,35 @@ export async function renderPhoto(const { ImageManipulator, SaveFormat } = await import("expo-image-manipulator");let image = await ImageManipulator.manipulate(uri).renderAsync();try {- const fittedSize = fitImageAttachmentSize(image);- if (fittedSize !== null) {- const resized = await ImageManipulator.manipulate(image).resize(fittedSize).renderAsync();- image.release();- image = resized;- }- const saved = await image.saveAsync({- format: format === "png" ? SaveFormat.PNG : SaveFormat.JPEG,- compress: PHOTO_JPEG_QUALITY,- base64: true,- });- if (!saved.base64) {- throw new Error("The rendered photo has no bytes.");+ let size = fitImageAttachmentSize(image);+ for (let shrinks = 0; ; shrinks += 1) {+ if (size !== null) {+ const resized = await ImageManipulator.manipulate(image).resize(size).renderAsync();+ image.release();+ image = resized;+ }+ const saved = await image.saveAsync({+ format: format === "png" ? SaveFormat.PNG : SaveFormat.JPEG,+ compress: PHOTO_JPEG_QUALITY,+ base64: true,+ });+ if (!saved.base64) {+ throw new Error("The rendered photo has no bytes.");+ }+ // PNG ignores compress, so a resampled PNG can encode larger than its original.+ size =+ shrinks < MAX_BYTE_LIMIT_SHRINKS+ ? shrinkToByteLimit(image, estimateBase64ByteSize(saved.base64))+ : null;+ if (size === null) return { base64: saved.base64, uri: saved.uri };+ try {+ const { File } = await import("expo-file-system");+ const discarded = new File(saved.uri);+ if (discarded.exists) discarded.delete();+ } catch (error) {+ console.warn("[composer-images] could not remove discarded render", error);+ }}- return { base64: saved.base64, uri: saved.uri };} finally {image.release();}