@rytass/file-converter-adapter-image-resizer
Version:
Rytass Utils Storages Images Resizer
40 lines (37 loc) • 1.13 kB
JavaScript
import sharp from 'sharp';
import { Readable } from '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 Readable) {
file.pipe(converter);
}
if (file instanceof Buffer) {
return converter.toBuffer();
}
return converter;
}
}
export { ImageResizer };