97 lines
2.6 KiB
TypeScript
97 lines
2.6 KiB
TypeScript
import { createHash } from 'crypto';
|
|
import sharp, { Sharp } from 'sharp';
|
|
|
|
sharp.cache(false);
|
|
sharp.concurrency(1);
|
|
|
|
const WHITE = { r: 255, g: 255, b: 255 };
|
|
const JPEG_QUALITY = 82;
|
|
const WEBP_QUALITY = 80;
|
|
|
|
export interface RenderedVariant {
|
|
name: 'thumbnail' | 'crop' | 'optimized';
|
|
contentType: string;
|
|
extension: string;
|
|
body: Buffer;
|
|
width: number;
|
|
height: number;
|
|
sha256: string;
|
|
}
|
|
|
|
export class InvalidImageError extends Error {
|
|
constructor(reason: string) {
|
|
super(reason);
|
|
this.name = 'InvalidImageError';
|
|
}
|
|
}
|
|
|
|
export function fitInside(
|
|
width: number,
|
|
height: number,
|
|
box: number,
|
|
): { width: number; height: number } {
|
|
const scale = Math.min(box / width, box / height, 1);
|
|
return {
|
|
width: Math.max(1, Math.floor(width * scale)),
|
|
height: Math.max(1, Math.floor(height * scale)),
|
|
};
|
|
}
|
|
|
|
export async function renderVariants(
|
|
original: Buffer,
|
|
maxPixels: number,
|
|
): Promise<RenderedVariant[]> {
|
|
const open = (): Sharp =>
|
|
sharp(original, { failOn: 'error', limitInputPixels: maxPixels }).rotate();
|
|
try {
|
|
const meta = await sharp(original, { limitInputPixels: maxPixels }).metadata();
|
|
if (!meta.width || !meta.height) {
|
|
throw new InvalidImageError('image has no dimensions');
|
|
}
|
|
const swapped = (meta.orientation ?? 1) >= 5;
|
|
const width = swapped ? meta.height : meta.width;
|
|
const height = swapped ? meta.width : meta.height;
|
|
const thumb = fitInside(width, height, 256);
|
|
const large = fitInside(width, height, 1280);
|
|
const thumbnail = open()
|
|
.resize(thumb.width, thumb.height, { fit: 'fill' })
|
|
.flatten({ background: WHITE })
|
|
.jpeg({ quality: JPEG_QUALITY });
|
|
const crop = open()
|
|
.resize(128, 128, { fit: 'cover', position: 'centre' })
|
|
.flatten({ background: WHITE })
|
|
.jpeg({ quality: JPEG_QUALITY });
|
|
const optimized = open()
|
|
.resize(large.width, large.height, { fit: 'fill' })
|
|
.webp({ quality: WEBP_QUALITY, effort: 4 });
|
|
return [
|
|
await finish('thumbnail', 'image/jpeg', 'jpg', thumbnail),
|
|
await finish('crop', 'image/jpeg', 'jpg', crop),
|
|
await finish('optimized', 'image/webp', 'webp', optimized),
|
|
];
|
|
} catch (error) {
|
|
if (error instanceof InvalidImageError) {
|
|
throw error;
|
|
}
|
|
throw new InvalidImageError(error instanceof Error ? error.message : 'decode failed');
|
|
}
|
|
}
|
|
|
|
async function finish(
|
|
name: RenderedVariant['name'],
|
|
contentType: string,
|
|
extension: string,
|
|
pipeline: Sharp,
|
|
): Promise<RenderedVariant> {
|
|
const { data, info } = await pipeline.toBuffer({ resolveWithObject: true });
|
|
return {
|
|
name,
|
|
contentType,
|
|
extension,
|
|
body: data,
|
|
width: info.width,
|
|
height: info.height,
|
|
sha256: createHash('sha256').update(data).digest('hex'),
|
|
};
|
|
}
|