Created
August 26, 2023 14:02
-
-
Save electerious/111bf7043385ef283ab2024ece3f8cca to your computer and use it in GitHub Desktop.
Image processing with Node.js and sharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { parse, format } from 'path' | |
import Progress from 'cli-progress' | |
import sharp from 'sharp' | |
const fit = process.argv[2] | |
const width = parseInt(process.argv[3]) | |
const height = parseInt(process.argv[4]) | |
const paths = process.argv.splice(5) | |
const toFile = (path) => { | |
const fileIn = parse(path) | |
const fileOut = parse( | |
format({ | |
dir: fileIn.dir, | |
name: `${fileIn.name}-${fit}-${width}-${height}`, | |
ext: `.avif`, | |
}) | |
) | |
return { | |
fileIn, | |
fileOut, | |
} | |
} | |
const bar = new Progress.SingleBar({}) | |
bar.start(paths.length, 0) | |
const results = await Promise.allSettled( | |
paths.map((path) => { | |
const { fileIn, fileOut } = toFile(path) | |
return sharp(format(fileIn)) | |
.resize(width, height, { | |
fit, | |
}) | |
.toFormat('avif', { | |
quality: 50, | |
chromaSubsampling: '4:2:0', | |
}) | |
.toFile(format(fileOut)) | |
.catch((error) => { | |
// Enhance error with details about the image that failed to process | |
throw new AggregateError([error], `Failed to process image '${format(fileIn)}'`) | |
}) | |
.finally(() => { | |
bar.increment() | |
}) | |
}) | |
) | |
bar.stop() | |
const rejections = results.filter((result) => result.status === 'rejected') | |
if (rejections.length > 0) { | |
rejections.forEach((result) => console.error(result.reason)) | |
process.exit(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment