How to overlay an image over another in Node Jimp?

Node.jsServer Side ProgrammingProgramming

The composite() method overlays an image over another Jimp image at the given x, y coordinates. The image will be placed at the given position of coordinates from where we can

Syntax

composite( src, x, y, [{ mode, opacitySource, opacityDest }] );

Definition of composite() paramters

  • src – The src defines the source location of the file where this image is located. It can be a local location or a remote location.

  • x, y – Coordinates that signify where to put the file.

  • mode – You can define a mode here for the image. For example,Jimp.BLEND_SOURCE_OVER – This mode will try to blend the new image into old image.

  • opacityDest – This will define the opacity of the destination image, i.e., the image on which this new image is placed.

  • opacitySource – This will define the opacity of the source image, i.e., the opacity of the new image.

Input Image

Overlay Image

Using Node JIMP – GREYSCALE()

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

  • Use node imageOverlay.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 imageOverlay(imageOverlay) { // Function name is same as of file
name
// Reading watermark Image
   let watermark = await Jimp.read(imageOverlay);
   watermark = watermark.resize(150,150); // Resizing watermark image
// Reading original image
   const image = await Jimp.read('/home/jimp/tutorials_point_img.jpg');
   watermark = await watermark
   image.composite(watermark, 0, 0, {
      mode: Jimp.BLEND_SOURCE_OVER,
      opacityDest: 1,
      opacitySource: 0.5
   })
   await image.writeAsync('/home/jimp/newImage.png');
}

// Calling this function using async
imageOverlay('/home/jimp/overlay_image.png');
console.log("Image is processed successfully");

Output

raja
Published on 27-Apr-2021 13:32:15
Advertisements