Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / image-crop.ts

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