Created
March 9, 2021 15:59
-
-
Save tvthatsme/166e54d7ac956d2f69b67362efd06ed9 to your computer and use it in GitHub Desktop.
Image Conversion
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
const fs = require("fs"); | |
const sharp = require("sharp"); | |
const arguments = process.argv.slice(2); | |
const directory = arguments[0]; | |
// This function is probably the useful part | |
async function convertToFormats(input, output) { | |
await sharp(input) | |
.avif({ quality: 80, speed: 3 }) | |
.toFile(`${output}.avif`) | |
.then(() => console.log(`${output}.avif ... done`)); | |
await sharp(input) | |
.webp({ quality: 80, lossless: true }) | |
.toFile(`${output}.webp`) | |
.then(() => console.log(`${output}.webp ... done`)); | |
await sharp(input) | |
.png() | |
.toFile(`${output}.png`) | |
.then(() => console.log(`${output}.png ... done`)); | |
} | |
// Reading some nested directories looking for images (not validating) | |
// and using the sub-directory name to determine the file name. | |
// This part is super-specific and probably not useful to keep... | |
fs.readdirSync(directory).map((file) => { | |
const subdir = `${directory}/${file}`; | |
const isSubDirectory = fs.lstatSync(subdir).isDirectory(); | |
if (isSubDirectory && file !== "output") { | |
fs.readdirSync(subdir).forEach((innerFile) => { | |
const thisFile = `${subdir}/${innerFile}`; | |
const newFilename = `tc-${file}-${innerFile.match(/\d+/)[0]}w`; | |
const newFileLocation = `${directory}/output/${newFilename}`; | |
convertToFormats(thisFile, newFileLocation); | |
}); | |
} | |
}, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment