// Receipt photos (SPEC.md ยง9): shrink and re-encode on the device, which // also strips EXIF metadata including GPS location, then encrypt. export interface ProcessedPhoto { full: Blob; thumb: Blob; w: number; h: number; } async function encode(canvas: HTMLCanvasElement, quality: number): Promise { const webp = await new Promise((r) => canvas.toBlob(r, 'image/webp', quality)); // Browsers that can't encode WebP silently return PNG; use JPEG instead. if (webp && webp.type === 'image/webp') return webp; const jpeg = await new Promise((r) => canvas.toBlob(r, 'image/jpeg', quality)); if (!jpeg) throw new Error('could not encode image'); return jpeg; } function draw(img: ImageBitmap, maxEdge: number): HTMLCanvasElement { const scale = Math.min(1, maxEdge / Math.max(img.width, img.height)); const c = document.createElement('canvas'); c.width = Math.round(img.width * scale); c.height = Math.round(img.height * scale); c.getContext('2d')!.drawImage(img, 0, 0, c.width, c.height); return c; } /** * Photo + thumbnail, together under `maxBytes` (minus encryption overhead). * Tries lower quality, then smaller sizes, before giving up. */ export async function processPhoto(file: Blob, maxBytes: number): Promise { const img = await createImageBitmap(file, { imageOrientation: 'from-image' }); try { const thumb = await encode(draw(img, 320), 0.7); const budget = maxBytes - thumb.size - 1024; for (const edge of [1600, 1280, 1024, 800]) { const canvas = draw(img, edge); for (const q of [0.82, 0.7, 0.55]) { const full = await encode(canvas, q); if (full.size <= budget) return { full, thumb, w: canvas.width, h: canvas.height }; } } throw new Error('too large'); } finally { img.close(); } }