Skip to content

Instantly share code, notes, and snippets.

@macrat
Created May 4, 2020
Embed
What would you like to do?
sharp vs jimp vs jimp + imagemin: compare output file size.
const path = require('path');
const {promises: fs} = require('fs');
const Jimp = require('jimp');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminWebp = require('imagemin-webp');
const imageminZopfli = require('imagemin-zopfli');
const Sharp = require('sharp');
async function files() {
return await fs.readdir('./images');
}
async function jimpConvert(original, mimetype, compressor=(img => img)) {
const img = await Jimp.read(original);
const buf = await img.getBufferAsync(mimetype);
return await compressor(buf);
}
async function sharpConvert(original, format) {
return await Sharp(original)
.toFormat(format)
.toBuffer();
}
function showTest(results) {
results.sort((x, y) => {
return x[1].length - y[1].length;
});
results.forEach(([label, image]) => {
console.log(label, image.length.toLocaleString());
});
}
(async () => {
for (const file of await files()) {
if (!file.match(/\.(jpg|jpeg|png|webp)$/)) {
continue;
}
const original = await fs.readFile(path.join('./images', file));
console.log(file);
showTest([
['original: ', original],
['sharp / jpeg: ', await sharpConvert(original, 'jpeg')],
['sharp / png: ', await sharpConvert(original, 'png')],
['sharp / webp: ', await sharpConvert(original, 'webp')],
['jimp / jpeg: ', await jimpConvert(original, 'image/jpeg')],
['jimp / png: ', await jimpConvert(original, 'image/png')],
['imagemin-mozjpeg: ', await jimpConvert(original, 'image/jpeg', imageminMozjpeg())],
['imagemin-zopfli: ', await jimpConvert(original, 'image/png', imageminZopfli())],
['imagemin-webp: ', await jimpConvert(original, 'image/png', imageminWebp())],
]);
console.log();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment