// Preparing page photos in the browser before upload. // The vision models read images at most ~1.15 megapixels, so a bigger upload only costs bandwidth. const MAX_PIXELS = 1.15e6; const MAX_SIDE = 1568; // Decode, shrink and re-encode as JPEG (also strips EXIF, e.g. location). export async function toJpeg(file) { let bitmap; try { bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); } catch { throw new Error(`Obrázek „${file.name}“ se nepodařilo otevřít${/\.hei[cf]$/i.test(file.name) ? " (formát HEIC – zkuste fotku uložit jako JPEG)" : ""}.`); } const scale = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height), Math.sqrt(MAX_PIXELS / (bitmap.width * bitmap.height))); const canvas = document.createElement("canvas"); canvas.width = Math.round(bitmap.width * scale); canvas.height = Math.round(bitmap.height * scale); canvas.getContext("2d").drawImage(bitmap, 0, 0, canvas.width, canvas.height); bitmap.close(); return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Převod obrázku selhal."))), "image/jpeg", 0.88)); } // Fingerprint of a file's bytes, to spot the same photo picked twice. // crypto.subtle exists only on https/localhost, so fall back to FNV-1a there. export async function fingerprint(file) { const buf = await file.arrayBuffer(); if (globalThis.crypto?.subtle) { const h = new Uint8Array(await crypto.subtle.digest("SHA-256", buf)); return [...h].map((b) => b.toString(16).padStart(2, "0")).join(""); } const bytes = new Uint8Array(buf); let h1 = 0x811c9dc5, h2 = 0x01000193 ^ bytes.length; for (let i = 0; i < bytes.length; i++) { h1 = Math.imul(h1 ^ bytes[i], 0x01000193); h2 = Math.imul(h2 ^ bytes[bytes.length - 1 - i], 0x01000193); } return `${bytes.length}-${(h1 >>> 0).toString(16)}-${(h2 >>> 0).toString(16)}`; }