import * as path from 'path' import * as fs from 'fs' import { wrapper, changeExtension, TypeOnEveryFile, TypeToolOptions, TypeToolProp, TypeOnBody, } from '@asset-toolkit/core' import sharp from 'sharp' export interface TypeProps extends TypeToolOptions { mode?: 'joinChannel' resize?: sharp.ResizeOptions trim?: number output?: { format: 'png' | 'jpg' | 'webp' | string png?: sharp.PngOptions jpg?: sharp.JpegOptions webp?: sharp.WebpOptions } settings?: sharp.SharpOptions } /** * A tool to Image Transform * @param props - { pathIn, pathOut } * @param options - { } * @returns { Promise(returns) } */ const imageTransform: (_props: TypeToolProp, options?: TypeProps) => Promise = wrapper( ({ pathIn, pathOut, file, options, next, log }: TypeOnEveryFile) => { const opts = { ...options, } const { resize, trim, output, settings } = opts log(file) const processor = sharp(path.resolve(pathIn || pathOut, file), settings) let ext: string | undefined = undefined if (resize) processor.resize(resize) if (trim) processor.trim(trim) if (output) { if (output.format === 'webp') { ext = '.webp' processor.webp(output.webp || { lossless: true }) } else if (output.format === 'jpg') { ext = '.jpg' processor.jpeg(output.jpg || { mozjpeg: true }) } else if (output.format === 'png') { ext = '.png' processor.png(output.png) } else { processor.toFormat(output.format) } } processor.toFile(path.resolve(pathOut, changeExtension(file, ext)), (err, info) => { if (err) console.log(err) log(JSON.stringify(info)) next() }) }, ({ pathIn, pathOut, options, log }: TypeOnBody) => { const { mode } = options if (mode === 'joinChannel') { const files: string[] = [] fs.readdirSync(pathOut).map((file: string) => { files.push(file) }) const [firsImage, ...nextImages] = files const processor = sharp(path.resolve(pathIn || pathOut, firsImage)) log(firsImage) return new Promise(resolve => { processor .joinChannel( nextImages .map((file: string) => { log(file) return fs.readFileSync(path.resolve(pathIn || pathOut, file)) }) .reverse(), ) .toFile(path.resolve(pathOut, files[0]), (err, info) => { if (err) console.log(err) log(JSON.stringify(info)) resolve() }) }) } }, { exts: ['jpeg', 'jpg', 'png', 'webp', 'avif', 'tiff'], name: 'Image Transform' }, ) export default imageTransform