Branchwell

Lumen & Gesso / website / app / lib / image-processing.ts

1import 'server-only';
2import { getCloudflareContext } from '@opennextjs/cloudflare';
3
4type Dimensions = { width: number; height: number };
5type RasterInfo = Dimensions & { format: string };
6type Bounds = Dimensions & { left: number; top: number };
7type Margins = { left: number; top: number; right: number; bottom: number };
8type ImageFit = 'scale-down' | 'squeeze';
9
10type ImageTransform = Partial<Dimensions> & { fit?: ImageFit; trim?: Margins };
11type ImageOutput =
12 | { format: 'image/png'; anim: false }
13 | { format: 'image/jpeg'; quality: number; background?: string; anim: false };
14type ImageTransformer = {
15 transform(options: ImageTransform): ImageTransformer;
16 draw(overlay: ReadableStream<Uint8Array>, options: { left: number; top: number }): ImageTransformer;
17 output(options: ImageOutput): Promise<{ response(): Response }>;
18};
19type WorkerImageResources = {
20 IMAGES?: {
21 input(source: ReadableStream<Uint8Array>): ImageTransformer;
22 info(source: ReadableStream<Uint8Array>): Promise<RasterInfo | { format: 'image/svg+xml' }>;
23 };
24 rasterizeSvg?: (svg: string) => Promise<Uint8Array>;
25};
26
27function workerImages() {
28 if (!process.env.CLOUDFLARE_DEPLOYMENT_ENV) return undefined;
29 const { IMAGES, rasterizeSvg } = getCloudflareContext().env as WorkerImageResources;
30 if (!IMAGES || !rasterizeSvg) throw new Error('Cloudflare image processing is unavailable.');
31 return { binding: IMAGES, rasterizeSvg };
32}
33
34async function nodeImage(bytes: Buffer, limitInputPixels?: number) {
35 const { default: sharp } = await import('sharp');
36 return sharp(bytes, limitInputPixels ? { limitInputPixels } : undefined);
37}
38
39function stream(bytes: Uint8Array): ReadableStream<Uint8Array> {
40 return new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); } });
41}
42
43async function output(transform: ImageTransformer, format: ImageOutput): Promise<Buffer> {
44 return Buffer.from(await (await transform.output(format)).response().arrayBuffer());
45}
46
47export async function imageDimensions(input: Buffer): Promise<Partial<Dimensions>> {
48 const worker = workerImages();
49 if (!worker) return (await nodeImage(input)).metadata();
50 const info = await worker.binding.info(stream(input));
51 return 'width' in info ? { width: info.width, height: info.height } : {};
52}
53
54export async function cropImage(input: Buffer, source: Dimensions, crop: Bounds): Promise<Buffer> {
55 const worker = workerImages();
56 if (!worker) return (await nodeImage(input)).extract(crop).png().toBuffer();
57 const trim = {
58 left: crop.left, top: crop.top,
59 right: source.width - crop.left - crop.width, bottom: source.height - crop.top - crop.height,
60 };
61 return output(worker.binding.input(stream(input)).transform({ trim }), { format: 'image/png', anim: false });
62}
63
64export async function encodePhotoJpeg(input: Buffer, quality: number, edge?: number): Promise<Buffer> {
65 const worker = workerImages();
66 if (!worker) {
67 const image = await nodeImage(input);
68 if (edge) image.autoOrient().resize(edge, edge, { fit: 'inside', withoutEnlargement: true });
69 return image.flatten({ background: '#ffffff' }).jpeg({ quality, mozjpeg: !edge }).toBuffer();
70 }
71 const image = worker.binding.input(stream(input));
72 const sized = edge ? image.transform({ width: edge, height: edge, fit: 'scale-down' }) : image;
73 return output(sized, { format: 'image/jpeg', quality, background: '#ffffff', anim: false });
74}
75
76export async function encodeReviewPhoto(input: Buffer): Promise<Buffer | null> {
77 const worker = workerImages();
78 const target = 1600;
79 const maxPixels = 40_000_000;
80 if (!worker) {
81 const image = await nodeImage(input, maxPixels);
82 const { format } = await image.metadata();
83 if (!format || !['jpeg', 'png', 'webp'].includes(format)) return null;
84 return image.rotate().resize({ width: target, height: target, fit: 'inside', withoutEnlargement: true })
85 .flatten({ background: '#fff' }).jpeg({ quality: 84 }).toBuffer();
86 }
87
88 const info = await worker.binding.info(stream(input));
89 if (!['image/jpeg', 'image/png', 'image/webp'].includes(info.format)) return null;
90 if (!('width' in info) || info.width * info.height > maxPixels) throw new Error('Review photo dimensions exceed the limit.');
91 const sized = worker.binding.input(stream(input)).transform({ width: target, height: target, fit: 'scale-down' });
92 return output(sized, { format: 'image/jpeg', quality: 84, background: '#ffffff', anim: false });
93}
94
95export async function upscalePrintImage(input: Buffer, source: Dimensions, longEdge: number) {
96 const worker = workerImages();
97 if (!worker) {
98 const size = source.width >= source.height ? { width: longEdge } : { height: longEdge };
99 return (await nodeImage(input)).resize({ ...size, kernel: 'lanczos3' }).png().toBuffer({ resolveWithObject: true });
100 }
101 const scale = longEdge / Math.max(source.width, source.height);
102 const width = Math.max(1, Math.round(source.width * scale));
103 const height = Math.max(1, Math.round(source.height * scale));
104 const resized = worker.binding.input(stream(input)).transform({ width, height, fit: 'squeeze' });
105 const data = await output(resized, { format: 'image/png', anim: false });
106 const info = await worker.binding.info(stream(data));
107 if (!('width' in info) || info.width !== width || info.height !== height) {
108 throw new Error('Could not retain the requested print resolution.');
109 }
110 return { data, info };
111}
112
113function centeredFraming(width: number, height: number) {
114 const innerWidth = Math.round(width * 0.86);
115 const innerHeight = Math.round(height * 0.86);
116 return {
117 innerWidth, innerHeight,
118 left: Math.floor((width - innerWidth) / 2),
119 top: Math.floor((height - innerHeight) / 2),
120 };
121}
122
123export async function encodeMirroredFraming(input: Buffer): Promise<Buffer> {
124 const worker = workerImages();
125 if (!worker) {
126 const image = (await nodeImage(input)).rotate();
127 const { width, height } = (await image.metadata()).autoOrient;
128 const { innerWidth, innerHeight, left, top } = centeredFraming(width, height);
129 return image.resize(innerWidth, innerHeight, { fit: 'fill' }).extend({
130 top, bottom: height - innerHeight - top, left, right: width - innerWidth - left,
131 extendWith: 'mirror',
132 }).jpeg({ quality: 94, mozjpeg: true }).toBuffer();
133 }
134
135 const jpeg = { format: 'image/jpeg', quality: 94, anim: false } as const;
136 const oriented = await output(worker.binding.input(stream(input)), { ...jpeg, quality: 100 });
137 const info = await worker.binding.info(stream(oriented));
138 if (!('width' in info)) throw new Error('Could not read image dimensions for wider framing.');
139 const { width, height } = info;
140 const { innerWidth, innerHeight, left, top } = centeredFraming(width, height);
141 const resized = worker.binding.input(stream(oriented)).transform({ width: innerWidth, height: innerHeight, fit: 'squeeze' });
142 const centered = await output(resized, { ...jpeg, quality: 100 });
143 const url = 'data:image/jpeg;base64,' + centered.toString('base64');
144 const columns = [[left, -1], [left, 1], [left + 2 * innerWidth, -1]];
145 const rows = [[top, -1], [top, 1], [top + 2 * innerHeight, -1]];
146 // The SVG viewport clips the reflected tiles to the original canvas.
147 const tiles = rows.flatMap(([y, sy]) => columns.map(([x, sx]) =>
148 '<use href="#center" transform="translate(' + x + ' ' + y + ') scale(' + sx + ' ' + sy + ')"/>',
149 )).join('');
150 const svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' + width + '" height="' + height +
151 '"><defs><image id="center" width="' + innerWidth + '" height="' + innerHeight + '" xlink:href="' + url +
152 '"/></defs>' + tiles + '</svg>';
153 return output(worker.binding.input(stream(await worker.rasterizeSvg(svg))), jpeg);
154}