How to compress images using Imagemin

In this post, we will learn to compress popular images format like JPEG, PNG,… in Node.js development environment.

We are using NPM package called Imagemin and it’s supportive plugins to compress images for our project.

Imagemin is available in:

Imagemin plugins to use

Imagemin has two types of plugins lossy and lossless. Lossy plugins offers option to customise image compression levels to meet your needs which significantly reduce image file size (losing image quality). Most of web developers use lossy plugins to have greater file size savings to speedup loading browser time and saving bandwidth.

Lossless plugins compress images without losing any image data. To keep quality of images some uses lossless plugins, but do not reduces size of image file compare to lossless plugins.

Image FormatLossy Plugin(s)Lossless Plugin(s)
JPEGimagemin-mozjpegimagemin-jpegtran
PNGimagemin-pngquantimagemin-optipng
GIFimagemin-giflossyimagemin-gifsicle
SVGimagemin-svgo-
WebPimagemin-webp-

A list of possible Imagemin plugins can be found here.

Imagemin npm module

Here, we use the npm module which offers more configuration options, but you can try the CLI as a decent alternative if you want to try Imagemin without touching any code.

First make sure we have Node.js working development environment in our system.

Lossy plugin(s)

Install necessary dependencies:

npm install imagemin imagemin-mozjpeg imagemin-pngquant --save

Create a script file say imagemin-lossy.js:

const imagemin = require("imagemin");
const imageminMozjpeg = require("imagemin-mozjpeg");
const imageminPngquant = require("imagemin-pngquant");

(async () => {
  const files = await imagemin(["./input/*.{jpeg,jpg,png}"], {
    destination: "./output/",
    plugins: [
      imageminMozjpeg({ quality: 80 }),
      imageminPngquant({ quality: [0.6, 0.8] }),
    ],
  });

  console.log(files);
  //=> [{data: <Buffer 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}, …]
})();

Put images inside input folder and run script with following command:

node imagemin-lossy.js

It will output our compressed images in output folder.

Lossless plugin(s)

Install necessary dependencies:

npm install imagemin imagemin-jpegtran imagemin-optipng --save

Create a script file say imagemin-lossless.js:

const imagemin = require("imagemin");
const imageminJpegtran = require("imagemin-jpegtran");
const imageminOptipng = require("imagemin-optipng");

(async () => {
  const files = await imagemin(["./input/*.{jpeg,jpg,png}"], {
    destination: "./output/",
    plugins: [imageminJpegtran({ progressive: true }), imageminOptipng()],
  });

  console.log(files);
  //=> [{data: <Buffer 89 50 4e …>, destinationPath: 'build/images/foo.jpg'}, …]
})();

Put images inside input folder and run script with following command:

node imagemin-lossless.js

It will output our compressed images in output folder.

Further resources

Imagemin template on GitHub.