UNPKG

@rytass/file-converter-adapter-image-transcoder

Version:

Rytass Utils Storages Images Converter

38 lines (35 loc) 1.11 kB
import sharp from 'sharp'; import { Readable } from 'stream'; import { fromBuffer } from 'file-type'; import { SupportSources } from './constants.js'; import { UnsupportedSource } from './errors.js'; sharp.cache(false); class ImageTranscoder { options; constructor(options){ this.options = options; sharp.concurrency(options.concurrency ?? 1); } async convert(file) { let converter; if (file instanceof Buffer) { const extension = await fromBuffer(file); if (!extension || !~SupportSources.indexOf(extension.ext)) { throw new UnsupportedSource(); } converter = sharp(file); } else { converter = sharp(); } converter.toFormat(this.options.targetFormat, this.options); // Stream cannot throw when format not supported if (file instanceof Readable) { file.pipe(converter); } if (file instanceof Buffer) { return converter.toBuffer(); } return converter; } } export { ImageTranscoder };