Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

imageCompression.ts

467 lines15.0 KB

1import {
2 downscalableImageMimeType,
3 fitImageAttachmentSize,
4 IMAGE_ATTACHMENT_MAX_EDGE,
5} from "@t3tools/client-runtime/image-attachment-size";
6import {
7 IMAGE_DIMENSIONS_HEADER_BYTES,
8 readImageDimensions,
9} from "@t3tools/shared/imageDimensions";
10​
11const MAX_DIMENSION = IMAGE_ATTACHMENT_MAX_EDGE;
12export const MAX_STASH_IMAGE_DATA_URL_CHARS = 1_300_000;
13/**
14 * Ceiling on the *source* file handed to the re-encoder. File size is a
15 * proxy for pixel count, and decoding hundreds of megapixels into an
16 * ImageBitmap can OOM the tab — beyond this we refuse rather than risk it.
17 */
18export const MAX_COMPRESSIBLE_SOURCE_BYTES = 50 * 1024 * 1024;
19const MAX_HEIC_DECODE_PIXELS = 64_000_000;
20const MAX_HEIC_METADATA_BYTES = 1024 * 1024;
21const QUALITY_STEPS = [0.92, 0.85, 0.78, 0.68] as const;
22const FALLBACK_SCALE_STEPS = [0.75, 0.55] as const;
23const HEIC_IMAGE_MIME_TYPE = /^image\/hei(?:c|f)$/i;
24const HEIC_IMAGE_EXTENSION = /\.(?:heic|heif)$/i;
25​
26type ImageSize = { width: number; height: number };
27​
28export interface CompressedStashImage {
29 imageSize?: ImageSize;
30 dataUrl: string;
31 mimeType: string;
32 sizeBytes: number;
33 recompressed: boolean;
35​
36export type ImageCompressionFailureReason = "too-large" | "unreadable";
37​
38export type CompressStashImageResult =
39 | { ok: true; image: CompressedStashImage }
40 | { ok: false; reason: ImageCompressionFailureReason };
41​
42export type CompressImageFileResult =
43 | { ok: true; file: File; recompressed: boolean; imageSize?: ImageSize }
44 | { ok: false; reason: ImageCompressionFailureReason };
45​
46/** Finder and some browsers omit the MIME type when dragging HEIC photos. */
47export function isHeicImageFile(file: Pick<File, "name" | "type">): boolean {
48 if (HEIC_IMAGE_MIME_TYPE.test(file.type)) {
49 return true;
50 }
51 return (
52 (file.type === "" || file.type.toLowerCase() === "application/octet-stream") &&
53 HEIC_IMAGE_EXTENSION.test(file.name)
54 );
56​
57interface HeicMetadataBox {
58 payloadOffset: number;
59 endOffset: number;
61​
62function findHeicMetadataBox(
63 view: DataView,
64 startOffset: number,
65 endOffset: number,
66 type: number,
67): HeicMetadataBox | null {
68 let offset = startOffset;
69 while (offset + 8 <= endOffset) {
70 let size = view.getUint32(offset);
71 let headerSize = 8;
72 if (size === 1) {
73 if (offset + 16 > endOffset) return null;
74 const extendedSize = view.getBigUint64(offset + 8);
75 if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
76 size = Number(extendedSize);
77 headerSize = 16;
78 } else if (size === 0) {
79 size = endOffset - offset;
80 }
81 if (size < headerSize || size > endOffset - offset) return null;
82​
83 const nextOffset = offset + size;
84 if (view.getUint32(offset + 4) === type) {
85 return { payloadOffset: offset + headerSize, endOffset: nextOffset };
86 }
87 offset = nextOffset;
88 }
89 return null;
91​
92async function validateHeicImageDimensions(
93 file: File,
94): Promise<ImageCompressionFailureReason | null> {
95 const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer();
96 const view = new DataView(metadata);
97 const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461);
98 if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable";
99 const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270);
100 if (!properties) return "unreadable";
101 const containers = findHeicMetadataBox(
102 view,
103 properties.payloadOffset,
104 properties.endOffset,
105 0x6970636f,
106 );
107 if (!containers) return "unreadable";
108​
109 let offset = containers.payloadOffset;
110 let foundImageDimensions = false;
111 while (offset < containers.endOffset) {
112 const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065);
113 if (!image) break;
114 if (image.payloadOffset + 12 > image.endOffset) return "unreadable";
115 const width = view.getUint32(image.payloadOffset + 4);
116 const height = view.getUint32(image.payloadOffset + 8);
117 if (width === 0 || height === 0) return "unreadable";
118 if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large";
119 foundImageDimensions = true;
120 offset = image.endOffset;
121 }
122 return foundImageDimensions ? null : "unreadable";
124​
125export function readFileAsDataUrl(file: Blob): Promise<string> {
126 return new Promise((resolve, reject) => {
127 const reader = new FileReader();
128 reader.addEventListener("load", () => {
129 if (typeof reader.result === "string") {
130 resolve(reader.result);
131 return;
132 }
133 reject(new Error("Could not read image data."));
134 });
135 reader.addEventListener("error", () => {
136 reject(reader.error ?? new Error("Failed to read image."));
137 });
138 reader.readAsDataURL(file);
139 });
141​
142function dataUrlLength(blob: Blob): number {
143 return (
144 `data:${blob.type || "application/octet-stream"};base64,`.length + 4 * Math.ceil(blob.size / 3)
145 );
147​
148export function dataUrlToFile(dataUrl: string, name: string, mimeType: string): File {
149 const payload = dataUrl.slice(dataUrl.indexOf(",") + 1);
150 const binary = atob(payload);
151 const bytes = new Uint8Array(binary.length);
152 for (let index = 0; index < binary.length; index += 1) {
153 bytes[index] = binary.charCodeAt(index);
154 }
155 return new File([bytes], name, { type: mimeType });
157​
158function fileNameForMimeType(name: string, mimeType: string): string {
159 const extension = mimeType === "image/webp" ? ".webp" : ".jpg";
160 const dotIndex = name.lastIndexOf(".");
161 const base = dotIndex > 0 ? name.slice(0, dotIndex) : name;
162 return `${base}${extension}`;
164​
165function canRecompress(): boolean {
166 return (
167 typeof createImageBitmap === "function" &&
168 (typeof OffscreenCanvas === "function" || typeof document !== "undefined")
169 );
171​
172interface Canvas2D {
173 canvas: OffscreenCanvas | HTMLCanvasElement;
174 context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
176​
177function createCanvas(width: number, height: number): Canvas2D | null {
178 if (typeof OffscreenCanvas === "function") {
179 const canvas = new OffscreenCanvas(width, height);
180 const context = canvas.getContext("2d");
181 if (!context) return null;
182 return { canvas, context };
183 }
184 if (typeof document === "undefined") return null;
185 const canvas = document.createElement("canvas");
186 canvas.width = width;
187 canvas.height = height;
188 const context = canvas.getContext("2d");
189 if (!context) return null;
190 return { canvas, context };
192​
193async function encodeCanvas(
194 canvas: OffscreenCanvas | HTMLCanvasElement,
195 quality: number,
196 mimeType: string,
197): Promise<Blob | null> {
198 let blob: Blob | null;
199 if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
200 blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, mimeType, quality));
201 } else {
202 blob = await (canvas as OffscreenCanvas).convertToBlob({ type: mimeType, quality });
203 }
204 return blob?.type === mimeType ? blob : null;
206​
207const composerThumbnails = new WeakMap<File, Promise<string | null>>();
208​
209export function createComposerImageThumbnail(file: File): Promise<string | null> {
210 const cached = composerThumbnails.get(file);
211 if (cached) return cached;
212 const thumbnail = (async () => {
213 if (!canRecompress()) return null;
214 let bitmap: ImageBitmap | undefined;
215 try {
216 bitmap = await createImageBitmap(file);
217 const side = Math.min(bitmap.width, bitmap.height);
218 if (side <= 0) return null;
219 const dimension = Math.min(256, side);
220 const surface = createCanvas(dimension, dimension);
221 if (!surface) return null;
222 surface.context.drawImage(
223 bitmap,
224 (bitmap.width - side) / 2,
225 (bitmap.height - side) / 2,
226 side,
227 side,
228 0,
229 0,
230 dimension,
231 dimension,
232 );
233 const blob = await encodeCanvas(surface.canvas, 1, "image/png");
234 return blob ? await readFileAsDataUrl(blob) : null;
235 } catch {
236 return null;
237 } finally {
238 bitmap?.close();
239 }
240 })();
241 composerThumbnails.set(file, thumbnail);
242 return thumbnail;
244​
245async function encodeWithinBudget(
246 bitmap: ImageBitmap,
247 maxDimension: number,
248 budgetChars: number,
249 preferredMimeType?: "image/jpeg",
250): Promise<{ blob: Blob; mimeType: string; imageSize: ImageSize } | null> {
251 const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height));
252 const width = Math.max(1, Math.round(bitmap.width * scale));
253 const height = Math.max(1, Math.round(bitmap.height * scale));
254 const target = createCanvas(width, height);
255 if (!target) return null;
256​
257 // Probe WebP once; JPEG (no alpha) needs a white matte, so the fill has to
258 // happen before drawing and depends on which codec we end up using.
259 const mimeType =
260 preferredMimeType ??
261 ((await encodeCanvas(target.canvas, QUALITY_STEPS[0], "image/webp"))
262 ? "image/webp"
263 : "image/jpeg");
264​
265 if (mimeType === "image/jpeg") {
266 target.context.fillStyle = "#ffffff";
267 target.context.fillRect(0, 0, width, height);
268 }
269 target.context.drawImage(bitmap, 0, 0, width, height);
270​
271 for (const quality of QUALITY_STEPS) {
272 const encoded = await encodeCanvas(target.canvas, quality, mimeType);
273 if (!encoded) break;
274 if (dataUrlLength(encoded) <= budgetChars) {
275 return { blob: encoded, mimeType, imageSize: { width, height } };
276 }
277 }
278 return null;
280​
281type ReencodeResult =
282 | { ok: true; blob: Blob; mimeType: string; imageSize: ImageSize }
283 | { ok: false; reason: ImageCompressionFailureReason };
284​
285async function reencodeWithinBudget(
286 file: File,
287 budgetChars: number,
288 preferredMimeType?: "image/jpeg",
289): Promise<ReencodeResult> {
290 if (!canRecompress()) {
291 return { ok: false, reason: "too-large" };
292 }
293​
294 let bitmap: ImageBitmap;
295 try {
296 bitmap = await createImageBitmap(file);
297 } catch {
298 return { ok: false, reason: "unreadable" };
299 }
300​
301 try {
302 // Each pass shrinks relative to the *previous target*, capped by
303 // MAX_DIMENSION. Scaling a fixed ceiling instead would be a no-op for
304 // images already smaller than that ceiling — the fallback passes would
305 // all resolve to the source size and never actually reduce resolution.
306 const baseDimension = Math.min(MAX_DIMENSION, Math.max(bitmap.width, bitmap.height));
307 let encodeFailed = false;
308 for (const dimensionScale of [1, ...FALLBACK_SCALE_STEPS]) {
309 const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale));
310 let encoded: Awaited<ReturnType<typeof encodeWithinBudget>>;
311 try {
312 encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType);
313 } catch {
314 encodeFailed = true;
315 continue;
316 }
317 encodeFailed = false;
318 if (encoded) {
319 return {
320 ok: true,
321 blob: encoded.blob,
322 mimeType: encoded.mimeType,
323 imageSize: encoded.imageSize,
324 };
325 }
326 }
327 return { ok: false, reason: encodeFailed ? "unreadable" : "too-large" };
328 } finally {
329 bitmap.close();
330 }
332​
333export async function compressImageForStash(
334 file: File,
335 budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,
336): Promise<CompressStashImageResult> {
337 try {
338 if (dataUrlLength(file) <= budgetChars) {
339 return {
340 ok: true,
341 image: {
342 dataUrl: await readFileAsDataUrl(file),
343 mimeType: file.type,
344 sizeBytes: file.size,
345 recompressed: false,
346 },
347 };
348 }
349 const reencoded = await reencodeWithinBudget(file, budgetChars);
350 if (!reencoded.ok) {
351 return reencoded;
352 }
353 return {
354 ok: true,
355 image: {
356 dataUrl: await readFileAsDataUrl(reencoded.blob),
357 mimeType: reencoded.mimeType,
358 sizeBytes: reencoded.blob.size,
359 recompressed: true,
360 imageSize: reencoded.imageSize,
361 },
362 };
363 } catch {
364 return { ok: false, reason: "unreadable" };
365 }
367​
368async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: ImageSize } | null> {
369 const mimeType = downscalableImageMimeType(file.type);
370 if (!mimeType || !canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null;
371 let bitmap: ImageBitmap | undefined;
372 try {
373 const header = readImageDimensions(
374 new Uint8Array(await file.slice(0, IMAGE_DIMENSIONS_HEADER_BYTES).arrayBuffer()),
375 );
376 if (!header || !fitImageAttachmentSize(header)) return null;
377 bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
378 const imageSize = fitImageAttachmentSize(bitmap);
379 if (!imageSize) return null;
380 const target = createCanvas(imageSize.width, imageSize.height);
381 if (!target) return null;
382 target.context.imageSmoothingQuality = "high";
383 target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height);
384 const blob = await encodeCanvas(target.canvas, QUALITY_STEPS[0], mimeType);
385 if (!blob) return null;
386 return {
387 file: new File([blob], file.name, { type: mimeType, lastModified: file.lastModified }),
388 imageSize,
389 };
390 } catch {
391 return null;
392 } finally {
393 bitmap?.close();
394 }
396​
397export async function compressImageToByteLimit(
398 file: File,
399 maxBytes: number,
400 options?: { preferredMimeType?: "image/jpeg"; sourceSizeBytes?: number },
401): Promise<CompressImageFileResult> {
402 const fitted = await fitImageToMaxEdge(file);
403 if (fitted && fitted.file.size <= maxBytes) {
404 return { ok: true, file: fitted.file, recompressed: true, imageSize: fitted.imageSize };
405 }
406 if (!fitted && file.size <= maxBytes) {
407 return { ok: true, file, recompressed: false };
408 }
409 if ((options?.sourceSizeBytes ?? file.size) > MAX_COMPRESSIBLE_SOURCE_BYTES) {
410 return { ok: false, reason: "too-large" };
411 }
412 const budgetChars = Math.floor(maxBytes / 3) * 4;
413 const reencoded = await reencodeWithinBudget(
414 fitted?.file ?? file,
415 budgetChars,
416 options?.preferredMimeType,
417 );
418 if (!reencoded.ok) {
419 return reencoded;
420 }
421 return {
422 ok: true,
423 file: new File(
424 [reencoded.blob],
425 fileNameForMimeType(file.name || "image", reencoded.mimeType),
426 { type: reencoded.mimeType },
427 ),
428 recompressed: true,
429 imageSize: reencoded.imageSize,
430 };
432​
433export async function prepareImageForAttachment(
434 file: File,
435 maxBytes: number,
436): Promise<CompressImageFileResult> {
437 if (!isHeicImageFile(file)) {
438 return compressImageToByteLimit(file, maxBytes);
439 }
440​
441 if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) {
442 return { ok: false, reason: "too-large" };
443 }
444​
445 let converted: Blob;
446 try {
447 const dimensionError = await validateHeicImageDimensions(file);
448 if (dimensionError) {
449 return { ok: false, reason: dimensionError };
450 }
451 const { heicTo } = await import("heic-to/csp");
452 converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] });
453 } catch {
454 return { ok: false, reason: "unreadable" };
455 }
456​
457 const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), {
458 type: "image/jpeg",
459 lastModified: file.lastModified,
460 });
461 const result = await compressImageToByteLimit(jpeg, maxBytes, {
462 preferredMimeType: "image/jpeg",
463 sourceSizeBytes: file.size,
464 });
465​
466 return result.ok ? { ...result, recompressed: true } : result;