Node Image Processing
Nov 21, 2022
Nov 21, 2022
Recently I had added a gallery to my site. I didn't like the image processing for creating thumbnails with 11ty so I decided to make my own. In my .eleventy build files, I added a library called sharp. With it, image processing becomes very simple and speedy. Here's my code for generating thumbnails for my gallery images.
// Generate Thumbnails
console.log("Building Thumbnails With Sharp...")
const inputsDirectory = (__dirname + "/src/img/gallery/");
const outputsDirectory = (__dirname + "/src/img/thumbnails/");
fs.readdirSync(inputsDirectory).forEach((fileName) => {
const inputPath = inputsDirectory + fileName;
const outputPath = outputsDirectory + fileName;
sharp(inputPath)
.resize(300)
.jpeg({
quality: 70
})
.toFile(outputPath)
.then(()=>{console.log(fileName + " has been created as a thumbnail.")})
;
});
With the above snippet, this generates images that are 300px in width from each image and saves them to a thumbnail directory during my build pipeline.
This has worked for me and hopefully can lend a hand for those looking for a folder wide thumbnail generator.