How to adjust the contrast of an image using contrast() function in Node Jimp?


NodeJS – Contrast() is an inbuilt function that is used to adjust the contrast of images. It will increase or decrease the contrast based upon the input value that ranges from -1 to +1.

Syntax

contrast(n, cb)

Definition of contrast() paramters

  • – It will take n as an input for adjusting the contrast of the image, Possible values of n is between -1 and +1.

  • cb – This is an optional parameter that can be invoked after the compilation is complete.

Input Image

Using Node JIMP – CONTRAST()

Before proceeding to use contrast() functions, please check that the following statements are already executed for setting up the environment.

  • npm init -y // Initialising the Node environment

  • npm install jimp --save // Installing the jimp dependency

  • Create a contrast.js file and copy-paste the following code snippet in it.

  • Use node contrast.js to run the code.

Note: Note that the method name should match with the JS file name. Only then it will be able to call the desired method.

Example

const Jimp = require('jimp') ;

async function contrast() { // Function name is same as of file name
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.contrast(.4)
   .write('/home/jimp/contrast.jpg');
}

contrast(); // Calling the function here using async
console.log("Image is processed successfully");

Output

Using Node JIMP – Contrast() with 'cb' parameters

Example

const Jimp = require('jimp') ;

async function contrast() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.contrast(-0.5, function(err){
      if (err) throw err;
   })
   .write('/home/jimp/contrast.jpg');
}

contrast();
console.log("Image is processed successfully");

Output

Updated on: 27-Apr-2021

632 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements