Skip to content

Instantly share code, notes, and snippets.

@xettri
Created September 22, 2020 22:10
Show Gist options
  • Save xettri/3b921475cf4cc0d88a949db35367b372 to your computer and use it in GitHub Desktop.
Save xettri/3b921475cf4cc0d88a949db35367b372 to your computer and use it in GitHub Desktop.
Compress image using NodeJs
const fs = require("fs");
const imagemin = require("imagemin");
const mozjpeg = require("imagemin-mozjpeg");
const imageminWebp = require('imagemin-webp');
const sharp = require("sharp");
const isJpg = require("is-jpg");
const NEED_FORMAT = "jpeg";
const convertToFormat = async (input) => {
const starpInput = sharp(input);
if(NEED_FORMAT === "jpeg"){
if (isJpg(input)) return input;
return starpInput.jpeg().toBuffer();
} else {
return starpInput.webp().toBuffer();
}
};
function getPlugins(){
let plugins = [convertToFormat];
if(NEED_FORMAT === "jpeg"){
plugins.push(mozjpeg({ quality: 100, fastCrush: true, tune: "psnr" }));
} else {
plugins.push(imageminWebp())
}
}
const imageFileBuffer = async (buffer) => {
const miniBuffer = await imagemin.buffer(buffer, {
plugins: getPlugins()
});
return miniBuffer;
};
fs.readFile('./input.png', async (err, data) => {
if (err) throw err;
data = Buffer.from(data)
var output = await imageFileBuffer(data);
fs.writeFileSync(`output.${NEED_FORMAT}`,output)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment