logo

The next-generation blog, news, and article for you to start sharing your stories today!

How To Compress Image In Node JS

In this article we will learn how to compress image size in nodejs. We are using third party library https://www.npmjs.com/package/sharp . 

This library is very popular. So lets start

# Precautions

I am assuming that you have littlebit knowledge of expressjs or nodejs and javascript.

 

# Depencency

  • For image compression in nodejs we are depend on third party image processing library called Sharp
  • You can read more about this library here https://www.npmjs.com/package/sharp

 

# Source code

# Step 1.

Create a javascript file called compress.js under the root directory of the project. Later we will run this file using nodejs

/home/project/compress.js

Install the sharp library using NPM

npm install sharp --save
// /home/project/compress.js

// Import the depencendy

const sharp = require("sharp");

Directory structure like

/home

----------------/Project

---------------------------/ compress.js

---------------------------/ package.json

---------------------------image.jpeg // uncompressed image

Step 2.

Now create a function who actually compress the image

// /home/project/compress.js

// Import the depencendy

const sharp = require("sharp");

/** Function for compress the image **/
  async compress(imagePath = null) {
    try {
      if (this._isFile(imagePath)) {
        let imageAbsPath = path.resolve(imagePath);
        let originalFileName = path.basename(imageAbsPath);

        let descFolder =
          path.resolve(path.dirname(imageAbsPath), "..") +
          "/" +
          'thumb' +
          "_" +
          this._getQualityNameBYVal(photoQuality);
        if (!fs.existsSync(descFolder)) {
          fs.mkdirSync(descFolder);
        }
        let descFileName = `${descFolder}/${originalFileName}`;

        /** Compress image () **/
        let response = await sharp(imageAbsPath)
          .jpeg({ quality: photoQuality })
          .toFile(descFileName);
      }
    } catch (error) {
      throw error;
    }
  }

This Function will accept the image path and read the image. Make a thumbnail as compressed image size.

Step 3. 

In setp 3 we wll call the actuall function

// /home/project/compress.js

// Import the depencendy

const sharp = require("sharp");

/** Function for compress the image **/
  async compress(imagePath = null) {
    try {
      if (this._isFile(imagePath)) {
        let imageAbsPath = path.resolve(imagePath);
        let originalFileName = path.basename(imageAbsPath);

        let descFolder =
          path.resolve(path.dirname(imageAbsPath), "..") +
          "/" +
          'thumb' +
          "_" +
          this._getQualityNameBYVal(photoQuality);
        if (!fs.existsSync(descFolder)) {
          fs.mkdirSync(descFolder);
        }
        let descFileName = `${descFolder}/${originalFileName}`;

        /** Compress image () **/
        let response = await sharp(imageAbsPath)
          .jpeg({ quality: photoQuality })
          .toFile(descFileName);
      }
    } catch (error) {
      throw error;
    }
  }


// Call the function
compress('./image.jpeg');

# Utility function

This function will check if given image path is a file or a directory

_isFile(imagePath = null) {
    try {
      let stats = fs.statSync(imagePath);
      return stats.isFile();
    } catch (err) {
      console.error(err.stack);
      return false;
    }
  }

  _isDir(imagePath = null) {
    try {
      let stats = fs.lstatSync(imagePath);
      return stats.isDirectory();
    } catch (err) {
      console.error(err.stack);
      return false;
    }
  }

Step 4. 

Run the file

Now you can run this file using terminal

Go to terminal and open the directory in terminal

Hit command like

node compress.js

This execution will create a new file called thumb/image.jpeg. Which will less in actuall image size.

How To Compress Image In Node JS.

 

avatar

Vikram Parihar

An editor at Keyscript

Vikram Parihar is an senior software engineer. He is working since 2013 in web development technologies. He works in NodeJS, Angular, Vue, PHP, Laravel, Express JS and various popular technologies.