@rytass/file-converter-adapter-image-resizer
Version:
Rytass Utils Storages Images Resizer
42 lines (38 loc) • 1.17 kB
JavaScript
;
var sharp = require('sharp');
var stream = require('stream');
sharp.cache(false);
class ImageResizer {
options;
constructor(options = {
keepAspectRatio: true,
concurrency: 1
}){
if (!options.maxHeight && !options.maxWidth) throw new Error('Please provide at least one `maxWidth` or `maxHeight`');
this.options = options;
sharp.concurrency(this.options.concurrency ?? 1);
}
async convert(file) {
let converter;
if (file instanceof Buffer) {
converter = sharp(file);
} else {
converter = sharp();
}
converter.resize({
width: this.options.maxWidth,
height: this.options.maxHeight,
withoutEnlargement: true,
fit: this.options.keepAspectRatio ? 'inside' : 'cover'
});
// Stream cannot throw when format not supported
if (file instanceof stream.Readable) {
file.pipe(converter);
}
if (file instanceof Buffer) {
return converter.toBuffer();
}
return converter;
}
}
exports.ImageResizer = ImageResizer;