Skip to content

Instantly share code, notes, and snippets.

@mauriciomassaia
Last active March 10, 2022 23:00
Show Gist options
  • Save mauriciomassaia/ba1083981d157a4b7bf0f9b6c093fe6a to your computer and use it in GitHub Desktop.
Save mauriciomassaia/ba1083981d157a4b7bf0f9b6c093fe6a to your computer and use it in GitHub Desktop.
Using squoosh to optimise and resize images from a source folder to an output folder and keeps the same filename.
const { ImagePool } = require('@squoosh/lib')
const path = require('path')
const fs = require('fs-extra')
const srcFolder = path.join(__dirname, 'big')
const files = fs.readdirSync(srcFolder)
const outputFolder = path.join(__dirname, 'output')
fs.ensureDir(outputFolder)
fs.emptyDirSync(outputFolder)
const width = 400
const height = 400
const processImage = async (src, dest) => {
const imagePool = new ImagePool()
const imagePath = src
const image = imagePool.ingestImage(imagePath);
await image.decoded; //Wait until the image is decoded before running preprocessors.
const preprocessOptions = {
//When both width and height are specified, the image resized to specified size.
resize: {
enabled: true,
width,
height,
}
}
await image.preprocess(preprocessOptions);
const encodeOptions = {
mozjpeg: {}, //an empty object means 'use default settings'
jxl: {
quality: 90,
},
}
await image.encode(encodeOptions);
await imagePool.close();
const rawEncodedImage = (await image.encodedWith.mozjpeg).binary;
fs.writeFile(dest, rawEncodedImage);
}
const next = async (files) =>{
if (files.length > 0) {
const f = files.shift()
console.log('processing', f)
await processImage(path.join(srcFolder, f), path.join(outputFolder, f))
next(files)
} else {
console.log('end')
}
}
next(files)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment