Created
March 25, 2023 05:37
-
-
Save Sanjay007/3fcb404784915e5b150c8270494a27ae to your computer and use it in GitHub Desktop.
Compress Image using Nodejs to 100KB
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 sharp = require('sharp'); | |
const fs = require('fs'); | |
sharp('path/to/input/image.jpg') | |
.jpeg({ quality: 80 }) | |
.resize({ width: 800 }) | |
.toBuffer((err, buffer) => { | |
if (err) throw err; | |
if (buffer.length > 100 * 1024) { | |
sharp(buffer) | |
.jpeg({ quality: 60 }) | |
.toBuffer((err, buffer) => { | |
if (err) throw err; | |
fs.writeFile('path/to/output/image.jpg', buffer, (err) => { | |
if (err) throw err; | |
console.log('Image compressed successfully.'); | |
}); | |
}); | |
} else { | |
fs.writeFile('path/to/output/image.jpg', buffer, (err) => { | |
if (err) throw err; | |
console.log('Image compressed successfully.'); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment