import 'server-only'; import { cropImage, imageDimensions } from './image-processing'; // Crop an image to a target aspect ratio so the saved file matches the // customer's chosen frame exactly. AI image models return a 1:1 square // (1024×1024) regardless of product, but every framed product has its // own aspect (12×16 → 3:4, 8×10 → 4:5, 12×12 → 1:1, etc.). If we ship // the square to Prodigi as-is, the printer either letterboxes inside // the print area (ugly mat space) or stretches the artwork. Cropping // here means the file Prodigi prints is exactly what the customer // previewed in their frame. // // Strategy: // - Parse "W / H" from pricing.ts (e.g. '3 / 4') into a numeric ratio. // - For portrait targets (target ratio < source ratio): keep full // height, crop sides centered → preserves vertical head position // that the prompt anchored at ~25% from the top. // - For landscape targets (target ratio > source ratio): keep full // width, crop top + bottom centered. We don't currently offer // landscape sizes but the function handles it correctly. // - For matching aspects: no-op (returns source unchanged). export async function cropToAspect(input: Buffer, aspectStr: string): Promise { const match = aspectStr.match(/^\s*(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)\s*$/); if (!match) { // Unparseable aspect — bail and return source. Callers will end up // with the square (same as before this function existed). console.warn(`[image-crop] unparseable aspect "${aspectStr}", returning source unchanged`); return input; } const targetW = parseFloat(match[1]); const targetH = parseFloat(match[2]); if (!Number.isFinite(targetW) || !Number.isFinite(targetH) || targetW <= 0 || targetH <= 0) { return input; } const targetRatio = targetW / targetH; const meta = await imageDimensions(input); const srcW = meta.width; const srcH = meta.height; if (!srcW || !srcH) return input; const srcRatio = srcW / srcH; // Already matches (within rounding) → no-op. if (Math.abs(srcRatio - targetRatio) < 0.001) return input; let cropW: number; let cropH: number; if (targetRatio < srcRatio) { // Target is narrower than source (portrait from a square). // Keep full height, crop sides equally. cropH = srcH; cropW = Math.round(srcH * targetRatio); } else { // Target is wider than source (landscape from a square). // Keep full width, crop top + bottom equally. cropW = srcW; cropH = Math.round(srcW / targetRatio); } const left = Math.max(0, Math.floor((srcW - cropW) / 2)); const top = Math.max(0, Math.floor((srcH - cropH) / 2)); return cropImage(input, { width: srcW, height: srcH }, { left, top, width: cropW, height: cropH }); }