nodejs watermark image

  1. Install the required packages: To add a watermark to an image using Node.js, we need to first install the necessary packages. We can use the 'gm' package, which is a popular graphicsMagick/ImageMagick library for Node.js. To install, open the terminal and run the following command: npm install gm

  2. Import the required modules: After installing the 'gm' package, we need to import it into our Node.js script. In your script file, add the following line to import the 'gm' module: javascript const gm = require('gm');

  3. Read the input image: Next, we need to read the input image file that we want to add a watermark to. Use the following code to read the image: javascript gm('input.jpg')

  4. Add the watermark: Once we have the input image, we can add the watermark to it. Use the 'drawText' function from the 'gm' module to add text as the watermark. The following code adds a watermark text to the image: javascript .drawText(20, 20, 'Watermark Text')

  5. Set the watermark position and style: We can customize the position and style of the watermark text. The first two parameters of the 'drawText' function indicate the X and Y coordinates of the watermark on the image. You can adjust these values to change the position of the watermark. Additionally, you can set other properties like font, font size, and color to customize the style of the watermark.

  6. Write the output image: Finally, we need to save the modified image with the watermark. Use the 'write' function from the 'gm' module to save the image. The following code saves the modified image with the watermark: javascript .write('output.jpg', function (err) { if (!err) console.log('Watermark added successfully.'); });

  7. Run the script: Save the script file with a '.js' extension, and then run it using Node.js in the terminal. This will execute the script and add the watermark to the input image. You can check the output image file to see the result.

Note: Ensure that you have the necessary permissions to read the input image file and write the output image file. Also, make sure to replace 'input.jpg' with the actual path or name of your input image file, and 'output.jpg' with the desired name of the output image file.