Add watermark to image in Node.js

This tutorial will show you how to add image or text watermark to an image in Node.js. In some of the photos, you have seen text, images, logo, and pattern which is superimposed intentionally on that photo is called a watermark. The purpose of watermarks is to make it difficult to copy or use images without permission.

For this purpose, I will be using a module called Jimp (Javascript Image Manipulation Program). The npm installer provided jimp is used to process the image. To add watermark on the image I am going to use jimp-watermark which is a jimp based powerful watermark librery.

First of all, we have to initialize package.json file to record dependencies and hold valuable metadata of our project. For that, we need to open our command prompt and simply type there like below.

npm init -y

After that, we have to install jimp-watermark to add watermark on the image. Similarly, we need to open the command prompt and type there like below.

npm i jimp-watermark

To add image watermark:

let watermark = require('jimp-watermark');
let options = {
    'ratio': 0.6,
    'opacity': 0.6,
    'dstPath' : './watermark.jpg'
};
watermark.addWatermark('drst.jpg', 'test.png', options);

In the above program, I have imported jimp-watermark and then I have created an option object so that we can modify our watermark.

  • ratio specifies the watermark text. The value of it should be less than 1 . ‘sample watermark’ is the default.
  • opacityspecifies the color of the watermark text. It should be less than 1. ‘Grey’ is the default.
  • dstPath specifies the path of output. ‘watermark.{source file ext}’ is the default.

 

watermark.addWatermarkto add the watermark. The 1st path 'drst.jpg'is the image path and the 2nd path 'test.png'is the path of the watermark and options is an object which I created to modify our watermark. The argument options is optional.

To add text watermark:

let watermark = require('jimp-watermark');
let options = {
    'text': 'CodeSpeedy',
    'textSize': 6,
    'dstPath' : './watermark.jpg'
};
watermark.addTextWatermark('drst.jpg', options);
  • text specifies the text which we want to add as a watermark on the main image.
  • textSize specifies the size of the text over the main image. Its value should be 1 to 8.

'drst.jpg' path of the image on which we want to add the watermark.

Leave a Reply

Your email address will not be published. Required fields are marked *