-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Working creation and display of webp and resized jpgs
- Loading branch information
1 parent
e519120
commit beb682d
Showing
2 changed files
with
44 additions
and
14 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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`) | ||
}); |
This file contains 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