Last active
April 16, 2024 20:34
-
-
Save paulathevalley/39a087eaadbab0a2d01e5faf7303aa2d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// npm install sharp | |
const sharp = require('sharp') | |
/* | |
usage | |
```shell | |
node node-optimize-images.js ./src/assets/ image-name.jpg | |
``` | |
expected result: | |
./src/assets/image-name_2.jpg | |
*/ | |
// accept args from command line: https://nodejs.dev/learn/nodejs-accept-arguments-from-the-command-line | |
const args = process.argv.slice(2) | |
const pathToImageLocation = args[0]; | |
const fileName = args[1]; | |
const newFormat = args[2]; | |
function optimize(path, fileName) { | |
if (!path || !fileName) { | |
if (!path) { | |
console.error("Please enter the location to the image, ex. ./assets/") | |
} | |
if (!fileName) { | |
console.error("Please enter name of file to optimize, ex. image.jpg"); | |
} | |
return; | |
} | |
const imageSrc = pathToImageLocation + fileName; | |
const imageFormat = newFormat || fileName.split(".").at(-1); | |
let newFileName = fileName.split("."); | |
newFileName.pop() | |
newFileName = [...newFileName, imageFormat].join("_2."); | |
return sharp(imageSrc) | |
.toFormat(imageFormat, { | |
quality: 80, | |
compressOnly: true, | |
density: 72 | |
}) | |
.toFile(pathToImageLocation + newFileName) | |
.then((data) => console.log(data)); | |
} | |
optimize(pathToImageLocation, fileName) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment