export interface ResizeImageOptions { maxWidth?: number; maxHeight?: number; quality?: number; mimeType?: string; } const DEFAULT_OPTIONS: Required = { maxWidth: 1280, maxHeight: 1280, quality: 0.9, mimeType: "image/jpeg", }; /** * Redimensiona uma imagem no client preservando boa qualidade. * Retorna uma dataURL compactada para envio à IA. */ export async function resizeImageToDataURL( file: File, options: ResizeImageOptions = {}, ): Promise<{ dataUrl: string; width: number; height: number }> { const opts = { ...DEFAULT_OPTIONS, ...options }; const bitmap = await createImageBitmap(file); let { width, height } = bitmap; const ratio = Math.min(opts.maxWidth / width, opts.maxHeight / height, 1); if (ratio < 1) { width = Math.round(width * ratio); height = Math.round(height * ratio); } const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const ctx = canvas.getContext("2d"); if (!ctx) { throw new Error("Contexto 2D não disponível para redimensionamento."); } ctx.drawImage(bitmap, 0, 0, width, height); return { dataUrl: canvas.toDataURL(opts.mimeType, opts.quality), width, height, }; }