43 lines
1004 B
TypeScript
43 lines
1004 B
TypeScript
import sharp from "sharp";
|
|
import type { ProductTemplate } from "./products";
|
|
|
|
export interface ProcessedImage {
|
|
buffer: Buffer;
|
|
format: "png" | "tiff";
|
|
widthPx: number;
|
|
heightPx: number;
|
|
dpi: number;
|
|
sizeBytes: number;
|
|
}
|
|
|
|
/**
|
|
* Process an uploaded image for a given product template.
|
|
* Resizes to fit the print area at the correct DPI, converts to PNG with
|
|
* proper density metadata.
|
|
*/
|
|
export async function processImage(
|
|
inputBuffer: Buffer,
|
|
product: ProductTemplate
|
|
): Promise<ProcessedImage> {
|
|
const targetWidth = product.widthPx;
|
|
const targetHeight = product.heightPx;
|
|
|
|
const result = await sharp(inputBuffer)
|
|
.resize(targetWidth, targetHeight, {
|
|
fit: "contain",
|
|
background: { r: 255, g: 255, b: 255, alpha: 0 },
|
|
})
|
|
.withMetadata({ density: product.dpi })
|
|
.png()
|
|
.toBuffer();
|
|
|
|
return {
|
|
buffer: result,
|
|
format: "png",
|
|
widthPx: targetWidth,
|
|
heightPx: targetHeight,
|
|
dpi: product.dpi,
|
|
sizeBytes: result.length,
|
|
};
|
|
}
|