Automatically Compressing Images With NodeJs

Sharing is Caring

Over the years, I’ve worked on a number of projects where we deal with user or company provided images which are often very large resolutions which take a long time to download on mobile phones or or poor internet connections.

As a result, I’ve made suggestions of using services like Kraken.io which can automatically reduce the size of images with very few problems. Some times, companies aren’t willing to take on a minor SaaS licensing cost so I’ve created some simple code that’s generally good enough.

'use strict'

const compressImages = require('compress-images')

const INPUT_PATH = 'images/**/*.{jpg,JPG,jpeg,JPEG,png,svg,gif}'
const OUTPUT_PATH = 'images/reduced/'

compressImages(INPUT_PATH, OUTPUT_PATH, {compress_force: false, statistic: true, autoupdate: true}, false,
  {jpg: {engine: 'mozjpeg', command: ['-quality', '60']}},
  {png: {engine: 'pngquant', command: ['--quality=20-50']}},
  {svg: {engine: 'svgo', command: '--multipass'}},
  {gif: {engine: 'gifsicle', command: ['--colors', '64', '--use-col=web']}}, function () {}
)

Installation

Make sure that you run npm install compress-images from the project root. This will automatically install the compress-images node module.

Adapting Code for Your Use Case

You will need to adapt this code for your use case which is likely to be replacing new images as they come in. I recommend using a file watcher on an “in box” directory and then having a production or output directory that the code will copy to.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.