22 lines
735 B
JavaScript
22 lines
735 B
JavaScript
import sharp from 'sharp';
|
|
|
|
export function createSharpImageRenderer() {
|
|
return async function renderDerivative({ data, maxWidth }) {
|
|
if (!Buffer.isBuffer(data)) {
|
|
throw new TypeError('Image data must be provided as a Buffer.');
|
|
}
|
|
|
|
if (!Number.isInteger(maxWidth) || maxWidth <= 0) {
|
|
throw new TypeError('maxWidth must be a positive integer.');
|
|
}
|
|
|
|
const image = sharp(data);
|
|
const metadata = await image.metadata();
|
|
|
|
const targetWidth = metadata.width && metadata.width > maxWidth ? maxWidth : metadata.width ?? maxWidth;
|
|
const resized = targetWidth === metadata.width ? image : image.resize({ width: targetWidth, withoutEnlargement: true });
|
|
|
|
return resized.webp().toBuffer();
|
|
};
|
|
}
|