feat: add sharp-backed image rendering
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
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();
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user