From beb682deb9a90e2351097b9da4e7db21c31791cd Mon Sep 17 00:00:00 2001 From: curt-mitch-census Date: Fri, 15 Dec 2023 12:15:03 -0800 Subject: [PATCH] Working creation and display of webp and resized jpgs --- .github/sharp/sharp.js | 40 +++++++++++++++++++++++++++++++--------- _layouts/project.html | 18 +++++++++++++----- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/.github/sharp/sharp.js b/.github/sharp/sharp.js index 89a39221..50e4c788 100644 --- a/.github/sharp/sharp.js +++ b/.github/sharp/sharp.js @@ -1,15 +1,37 @@ const sharp = require('sharp'); const fs = require('fs'); +const path = require('path'); -const imgDir = '../../assets/img/heroes'; +const imgDir = '../../assets/img/projects/deploying-privacy-enhancing-technologies'; +const SHARP_FORMATS = ['jpeg', 'jpg', 'png', 'webp', 'gif', 'avif', 'tiff']; +const IMAGE_SIZES = [ + ['s', 300], + ['m', 700], + ['l', 1000], + ['xl', 1500], + ['xxl', 2500], +]; -console.log('cwd', process.cwd()); +fs.readdirSync(imgDir).map(async file => { + const filePath = `${imgDir}/${file}`; + // check if file is not an image format + if (!SHARP_FORMATS.includes(path.parse(filePath).ext.replace('.', ''))) return; -fs.readdirSync(imgDir).forEach(file => { - // check if file is an image type accepted by sharp - if (!file.match(/.(jpg|jpeg|png|gif)$/i)) return; + const sharpFile = sharp(filePath); + const filename = path.parse(filePath).name; + const fileExtension = path.parse(filePath).ext; - sharp(`${imgDir}/${file}`) - .resize(200, 100) // width, height - .toFile(`${imgDir}/${file}-small.jpg`); - }); + // create multiple sizes of original image + for (newSize of IMAGE_SIZES) { + const [sizeLabel, newWidth] = newSize; + + sharpFile + .resize(newWidth) // sharp will maintain aspect ratio + .toFile(`${imgDir}/${filename}-${sizeLabel}${fileExtension}`); + } + + // create webp version of original image + sharpFile + .toFormat('webp') + .toFile(`${imgDir}/${filename}.webp`) +}); diff --git a/_layouts/project.html b/_layouts/project.html index 17189aa0..831717b2 100644 --- a/_layouts/project.html +++ b/_layouts/project.html @@ -30,11 +30,19 @@

{{ page.title }}

- {{ page.img_alt_text }} + + + {{ page.img_alt_text }} +