// Copy of solvway-customer-portal/app/lib/kyc/resizeImage.ts (the portals share no package); keep the two in step. /** Resize a dimension so it fits within maxEdge while keeping aspect ratio. Never upscales. */ export function fitWithin(w: number, h: number, maxEdge: number): { width: number; height: number } { const maxDim = Math.max(w, h); if (maxDim <= maxEdge) return { width: w, height: h }; const scale = maxEdge / maxDim; return { width: Math.floor(w * scale), height: Math.floor(h * scale) }; } /** Resize a File to JPEG, returning base64 (data: prefix stripped), MIME type and byte count. */ export async function resizeToJpegBase64( file: File, maxEdge = 2000, quality = 0.85, ): Promise<{ base: string; fileType: "image/jpeg"; bytes: number }> { const bitmap = await createImageBitmap(file); const { width, height } = fitWithin(bitmap.width, bitmap.height, maxEdge); return new Promise((resolve, reject) => { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const ctx = canvas.getContext("2d"); if (!ctx) { reject(new Error("No canvas context")); return; } ctx.drawImage(bitmap, 0, 0, width, height); bitmap.close(); canvas.toBlob( (blob) => { if (!blob) { reject(new Error("toBlob returned null")); return; } const reader = new FileReader(); reader.onloadend = () => { const result = reader.result as string; // Strip the "data:image/...;base64," prefix const base = result.startsWith("data:") ? result.slice(result.indexOf(",") + 1) : result; resolve({ base, fileType: "image/jpeg", bytes: blob.size }); }; reader.onerror = () => reject(new Error("Failed to read blob")); reader.readAsDataURL(blob); }, "image/jpeg", quality, ); }); }