Last active
August 8, 2024 01:05
-
-
Save alobato/d06f5dd8d552a8a766abbc87a44c5aa4 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
const sharp = require('sharp'); | |
const fs = require('fs-extra'); | |
const path = require('path'); | |
// Directory containing the images | |
const inputDir = './'; | |
const outputDir = './optimized_images'; | |
// Ensure the output directory exists | |
fs.ensureDirSync(outputDir); | |
// Path to the MozJPEG binary | |
// const mozjpegPath = '/usr/local/bin/cjpeg'; // Adjust the path according to your MozJPEG installation | |
// Function to optimize an image using MozJPEG | |
async function optimizeImage(inputPath, outputPath) { | |
try { | |
const buffer = await sharp(inputPath) | |
.jpeg({ quality: 85, mozjpeg: true }) | |
.toBuffer(); | |
await fs.writeFile(outputPath, buffer); | |
console.log(`Optimized ${inputPath} -> ${outputPath}`); | |
} catch (error) { | |
console.error(`Error optimizing ${inputPath}:`, error); | |
} | |
} | |
// Process all .png and .jpg files in the directory | |
fs.readdir(inputDir, (err, files) => { | |
if (err) { | |
console.error('Error reading directory:', err); | |
return; | |
} | |
files.forEach(file => { | |
const ext = path.extname(file).toLowerCase(); | |
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg') { | |
const inputPath = path.join(inputDir, file); | |
const outputFilename = path.basename(file, ext) + '.jpg'; | |
const outputPath = path.join(outputDir, outputFilename); | |
optimizeImage(inputPath, outputPath); | |
} | |
}); | |
}); |
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
{ | |
"name": "optimize-images", | |
"version": "1.0.0", | |
"description": "Optimize images using sharp and mozjpeg", | |
"bin": "./index.js", | |
"dependencies": { | |
"sharp": "^0.33.4", | |
"fs-extra": "^11.2.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment