diff --git a/apps/web/src/lib/imageCanvas.ts b/apps/web/src/lib/imageCanvas.ts index 145a97341b48..a9f1b39ac146 100644 --- a/apps/web/src/lib/imageCanvas.ts +++ b/apps/web/src/lib/imageCanvas.ts @@ -194,28 +194,43 @@ export const encodeCanvasOnThisThread: EncodeCanvas = async ( return blob?.type === mimeType ? blob : null; }; -/** `null` when the image already fits, or the browser cannot draw or encode it. */ -export async function fitImageToMaxEdge( +/** macOS pastes a photo copied from an iPhone as a 16-bit PNG, several times its 8-bit size. */ +function isSixteenBitPng(header: Uint8Array): boolean { + return ( + header.length > 24 && + new DataView(header.buffer, header.byteOffset).getUint32(0) === 0x89504e47 && + header[24] === 16 + ); +} + +/** + * Redraws an image over the max edge, or a 16-bit PNG at its own size. `null` when there's + * nothing to gain, or the browser cannot draw or encode it. + */ +export async function fitImageForAttachment( file: Blob, mimeType: string, quality: number, encode: EncodeCanvas, ): Promise<{ blob: Blob; imageSize: ImageSize } | null> { - const header = readImageDimensions( - new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()), + const headerBytes = new Uint8Array( + await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer(), ); - if (!header || !fitImageAttachmentSize(header)) return null; + const header = readImageDimensions(headerBytes); + if (!header || (!fitImageAttachmentSize(header) && !isSixteenBitPng(headerBytes))) return null; const bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); try { - const imageSize = fitImageAttachmentSize(bitmap); - if (!imageSize) return null; + const scaledSize = fitImageAttachmentSize(bitmap); + const imageSize = scaledSize ?? { width: bitmap.width, height: bitmap.height }; const colorSpace = await readImageColorSpace(file); const target = createCanvas(imageSize.width, imageSize.height, colorSpace); if (!target) return null; target.context.imageSmoothingQuality = "high"; target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); const blob = await encode(target.canvas, colorSpace, quality, mimeType); - return blob ? { blob, imageSize } : null; + // The canvas writes RGBA, so a 16-bit grayscale PNG can come out larger at 8 bits. + if (!blob || (!scaledSize && blob.size >= file.size)) return null; + return { blob, imageSize }; } finally { bitmap.close(); } diff --git a/apps/web/src/lib/imageCompression.browser.test.ts b/apps/web/src/lib/imageCompression.browser.test.ts index fb4f90af5c9f..b7eafe75d088 100644 --- a/apps/web/src/lib/imageCompression.browser.test.ts +++ b/apps/web/src/lib/imageCompression.browser.test.ts @@ -13,12 +13,13 @@ async function makeImage( colorSpace: PredefinedColorSpace, fill: string, type: string, + { width = 2400, height = 1600, colorType = "unorm8" } = {}, ): Promise { - const canvas = new OffscreenCanvas(2400, 1600); - const context = canvas.getContext("2d", { colorSpace }); + const canvas = new OffscreenCanvas(width, height); + const context = canvas.getContext("2d", { colorSpace, colorType }); if (!context) throw new Error("no 2d context"); context.fillStyle = fill; - context.fillRect(0, 0, 2400, 1600); + context.fillRect(0, 0, width, height); const blob = await canvas.convertToBlob({ type, quality: 0.95 }); return new File([blob], `shot.${type.slice(6)}`, { type }); } @@ -135,6 +136,23 @@ describe("prepareImageForAttachment color", () => { await expectSameColors(result.file, source); }); + it("redraws a 16-bit Display P3 PNG at 8 bits per channel and keeps its colors", async () => { + const readBitDepth = async (png: Blob) => new Uint8Array(await png.arrayBuffer())[24]; + const source = await makeImage("display-p3", "color(display-p3 0 1 0)", "image/png", { + width: 300, + height: 400, + colorType: "float16", + }); + expect(await readBitDepth(source)).toBe(16); + + const result = await prepareImageForAttachment(source, 20 * 1024 * 1024); + if (!result.ok) throw new Error(result.reason); + expect(result.imageSize).toEqual({ width: 300, height: 400 }); + expect(result.file.type).toBe("image/png"); + expect(await readBitDepth(result.file)).toBe(8); + await expectSameColors(result.file, source); + }); + it("keeps Display P3 colors when the stash re-encodes a WebP", async () => { const source = await makeImage("display-p3", "color(display-p3 0 1 0)", "image/webp"); const result = await compressImageForStash( diff --git a/apps/web/src/lib/imageCompression.test.ts b/apps/web/src/lib/imageCompression.test.ts index 87ede29ea5be..2a89c4ee8633 100644 --- a/apps/web/src/lib/imageCompression.test.ts +++ b/apps/web/src/lib/imageCompression.test.ts @@ -401,7 +401,7 @@ describe("HEIC attachment preparation", () => { describe("attachment max edge", () => { const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]; const u16 = (n: number) => [(n >>> 8) & 0xff, n & 0xff]; - const pngHeader = (width: number, height: number) => [ + const pngHeader = (width: number, height: number, bitDepth = 8) => [ 0x89, 0x50, 0x4e, @@ -417,7 +417,7 @@ describe("attachment max edge", () => { 0x52, ...u32(width), ...u32(height), - 8, + bitDepth, 6, 0, 0, @@ -488,6 +488,17 @@ describe("attachment max edge", () => { expect(result.ok && result.imageSize).toEqual({ width: 1500, height: 2000 }); }); + it("keeps a 16-bit PNG whose 8-bit redraw comes out larger", async () => { + const { decode } = stubDecoder({ width: 1042, height: 1389 }); + const original = image(pngHeader(1042, 1389, 16), "image.png", "image/png"); + + const result = await prepareImageForAttachment(original, 10 * 1024 * 1024); + + expect(decode).toHaveBeenCalledOnce(); + expect(result.ok && result.file).toBe(original); + expect(result.ok && result.recompressed).toBe(false); + }); + it.each([ { label: "a 2000px PNG", header: pngHeader(2000, 1200), type: "image/png" }, { diff --git a/apps/web/src/lib/imageCompression.ts b/apps/web/src/lib/imageCompression.ts index e63d9800de3c..15610531369d 100644 --- a/apps/web/src/lib/imageCompression.ts +++ b/apps/web/src/lib/imageCompression.ts @@ -10,7 +10,7 @@ import { createCanvas, type EncodeCanvas, encodeCanvasOnThisThread, - fitImageToMaxEdge, + fitImageForAttachment, iccProfileIsDisplayP3, type ImageSize, MAX_IMAGE_METADATA_BYTES, @@ -468,7 +468,7 @@ export async function compressImageForStash( } } -async function fitImageFileToMaxEdge( +async function fitImageFileForAttachment( file: File, ): Promise<{ file: File; imageSize: ImageSize } | null> { const mimeType = downscalableImageMimeType(file.type); @@ -476,7 +476,9 @@ async function fitImageFileToMaxEdge( try { const fitted = (await runInImageWorker({ kind: "fit", file, mimeType, quality: QUALITY_STEPS[0] })) ?? - ({ value: await fitImageToMaxEdge(file, mimeType, QUALITY_STEPS[0], encodeCanvas) } as const); + ({ + value: await fitImageForAttachment(file, mimeType, QUALITY_STEPS[0], encodeCanvas), + } as const); if (!fitted.value) return null; return { file: new File([fitted.value.blob], file.name, { @@ -495,7 +497,7 @@ export async function compressImageToByteLimit( maxBytes: number, options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number }, ): Promise { - const fitted = await fitImageFileToMaxEdge(file); + const fitted = await fitImageFileForAttachment(file); if (fitted && fitted.file.size <= maxBytes) { return { ok: true, file: fitted.file, recompressed: true, imageSize: fitted.imageSize }; } diff --git a/apps/web/src/lib/imageCompression.worker.ts b/apps/web/src/lib/imageCompression.worker.ts index 96c3bcdbf7f1..902809c15615 100644 --- a/apps/web/src/lib/imageCompression.worker.ts +++ b/apps/web/src/lib/imageCompression.worker.ts @@ -1,6 +1,6 @@ import { encodeCanvasOnThisThread, - fitImageToMaxEdge, + fitImageForAttachment, type ImageSize, renderThumbnail, } from "./imageCanvas"; @@ -55,7 +55,12 @@ async function run(task: ImageWorkerTask): Promise