mindee
Version:
Mindee Client Library for Node.js
33 lines (32 loc) • 1.26 kB
JavaScript
import { loadOptionalDependency } from "../dependency/index.js";
import { MindeeImageError } from "../errors/index.js";
/**
* Compresses an image with the given parameters.
*
* @param imageBuffer Buffer representation of an image.
* @param quality Quality to apply to the image (JPEG).
* @param maxWidth Maximum bound for width.
* @param maxHeight Maximum bound for height.
*/
export async function compressImage(imageBuffer, quality = 85, maxWidth = null, maxHeight = null) {
const sharpLoaded = await loadOptionalDependency("sharp", "Image compression");
const sharp = sharpLoaded.default || sharpLoaded;
let sharpImage = sharp(imageBuffer);
const metadata = await sharpImage.metadata();
if (metadata.width === undefined || metadata.height === undefined) {
throw new MindeeImageError("Source image has invalid dimensions.");
}
maxWidth ?? (maxWidth = metadata.width);
maxHeight ?? (maxHeight = metadata.height);
if (maxWidth || maxHeight) {
sharpImage = sharpImage.resize({
width: maxWidth,
height: maxHeight,
fit: "inside",
withoutEnlargement: true,
});
}
return await sharpImage
.jpeg({ quality: quality })
.toBuffer();
}