mindee
Version:
Mindee Client Library for Node.js
37 lines (36 loc) • 1.39 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compressImage = compressImage;
const sharp_1 = __importDefault(require("sharp"));
const mindeeError_1 = require("../errors/mindeeError");
/**
* 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.
*/
async function compressImage(imageBuffer, quality = 85, maxWidth = null, maxHeight = null) {
let sharpImage = (0, sharp_1.default)(imageBuffer);
const metadata = await sharpImage.metadata();
if (metadata.width === undefined || metadata.height === undefined) {
throw new mindeeError_1.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();
}
;