Skip to content

Instantly share code, notes, and snippets.

@Sanjay007
Created March 25, 2023 05:37
Show Gist options
  • Save Sanjay007/3fcb404784915e5b150c8270494a27ae to your computer and use it in GitHub Desktop.
Save Sanjay007/3fcb404784915e5b150c8270494a27ae to your computer and use it in GitHub Desktop.
Compress Image using Nodejs to 100KB
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