How to change the opacity of an image in Node Jimp?

Node.jsServer Side ProgrammingProgramming

NodeJS – Opacity() is an inbuilt function that is used to change the opacity of the images. This function multiplies the opacity of each pixel by a factor between 0 and 1 to produce the output image.

Syntax

opacity(f, cb)

Definition of opacity() paramters

  • – It takes a value between 0 to 1 as an input which will the paramtere to make the image opaque. Input 1 will make the image completely transparent.

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

Input Image

Using Node JIMP – OPACITY()

Before proceeding to use opacity() 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 an opacity.js file and copy-paste the following code snippet in it.

  • Use node opacity.js to run the code.

Note − 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 opacity() { // Function name is same as of file name
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.opacity(0.7)
   .write('/home/jimp/opacity.png');
}

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

Output

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

Example

const Jimp = require('jimp') ;

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

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

Output

raja
Published on 27-Apr-2021 13:40:14
Advertisements