Last active
June 3, 2020 21:16
-
-
Save Deepak13245/6cf01898dc91f9f814db86edde61787c to your computer and use it in GitHub Desktop.
Optimize jpeg and png images
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 imagemin = require('imagemin'); | |
const imageminJpegTran = require('imagemin-jpegtran'); | |
const imageminPngQuant = require('imagemin-pngquant'); | |
const imageminJpegRecompress = require('imagemin-jpeg-recompress'); | |
const fs = require('fs'); | |
async function optimizeImageBuffer(buffer) { | |
return imagemin.buffer(buffer, { | |
plugins: [ | |
imageminJpegRecompress({ | |
quality: 'high', | |
}), | |
imageminJpegTran(), | |
imageminPngQuant({ | |
quality: [0.6, 0.8], | |
strip: true, | |
}), | |
] | |
}) | |
} | |
// Promisify is function is in another gist which converts callback fashion to promise fashion. | |
// https://gist.github.com/Deepak13245/129ecdbb72c9f0f81827eb421260a8da | |
const readFile = promisify(fs.readFile); | |
const writeFile = promisify(fs.writeFile); | |
async function optimizeImage(src, dest) { | |
const buffer = await readFile(src); | |
const optimizedBuffer = await optimizeImageBuffer(buffer); | |
await writeFile(dest, optimizedBuffer); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment