Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions apps/web/src/lib/imageCanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
24 changes: 21 additions & 3 deletions apps/web/src/lib/imageCompression.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ async function makeImage(
colorSpace: PredefinedColorSpace,
fill: string,
type: string,
{ width = 2400, height = 1600, colorType = "unorm8" } = {},
): Promise<File> {
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 });
}
Expand Down Expand Up @@ -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(
Expand Down
15 changes: 13 additions & 2 deletions apps/web/src/lib/imageCompression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -417,7 +417,7 @@ describe("attachment max edge", () => {
0x52,
...u32(width),
...u32(height),
8,
bitDepth,
6,
0,
0,
Expand Down Expand Up @@ -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" },
{
Expand Down
10 changes: 6 additions & 4 deletions apps/web/src/lib/imageCompression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
createCanvas,
type EncodeCanvas,
encodeCanvasOnThisThread,
fitImageToMaxEdge,
fitImageForAttachment,
iccProfileIsDisplayP3,
type ImageSize,
MAX_IMAGE_METADATA_BYTES,
Expand Down Expand Up @@ -468,15 +468,17 @@ export async function compressImageForStash(
}
}

async function fitImageFileToMaxEdge(
async function fitImageFileForAttachment(
file: File,
): Promise<{ file: File; imageSize: ImageSize } | null> {
const mimeType = downscalableImageMimeType(file.type);
if (!mimeType || !canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
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, {
Expand All @@ -495,7 +497,7 @@ export async function compressImageToByteLimit(
maxBytes: number,
options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
): Promise<CompressImageFileResult> {
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 };
}
Expand Down
9 changes: 7 additions & 2 deletions apps/web/src/lib/imageCompression.worker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
encodeCanvasOnThisThread,
fitImageToMaxEdge,
fitImageForAttachment,
type ImageSize,
renderThumbnail,
} from "./imageCanvas";
Expand Down Expand Up @@ -55,7 +55,12 @@ async function run(task: ImageWorkerTask): Promise<ImageWorkerResults[ImageWorke
case "encode":
return encodeBitmap(task);
case "fit":
return fitImageToMaxEdge(task.file, task.mimeType, task.quality, encodeCanvasOnThisThread);
return fitImageForAttachment(
task.file,
task.mimeType,
task.quality,
encodeCanvasOnThisThread,
);
case "thumbnail": {
const blob = await renderThumbnail(task.file, encodeCanvasOnThisThread);
return blob ? readAsDataUrl(blob) : null;
Expand Down
Loading