How to create a watermarked Image in NodeJS using Canvas?

Sahil Paudel
Codantastic
Published in
2 min readMay 27, 2020

--

Today, we will see how can we use a watermark image and paste it over a given image.

Why we need a watermark?
Have you ever visited a premium image website or say Shutterstock they have there brand name written over all the images. What does that tell you? It tells that the image is the property of Shutterstock, not only Shutterstock there multiple such sites on the internet where the image is watermarked with their brand name.

Let's write a code that does that.

Requirements
1. 2 images (1 watermark image, 1 the image you want to watermarked)
2. Knowledge on NodeJS (Obviously you know that)
3. Canvas (Yes and a Paint Brush, your code)

Watermark Image (Source: Own Creation)
Target Image (Source: Personal Photo)
Result Watermarked Image

Now let’s dive right into the code.

"canvas": "^2.6.1" // version I am using.

Line: 5, Create a canvas with specified height and width.
Line: 6, Get the 2D context of the created canvas.
Line: 9, load the target image using the async loadImage function.
Line: 12, draw the target file in the canvas with dimension passed in the function.
Line: 15, load the watermark image, the same way we loaded the target image.
Line: 18, now draw the watermark image on the same canvas we drew the target file. As the watermark image is transparent we get the desired image as output.
Line: 20, It will create a buffer of the output image, we need to save it as an image somewhere. Code to save as image below.

We have imported the util function we wrote earlier and called it by passing the required parameters and saved the image locally.

Hope you liked it :)

--

--

Sahil Paudel
Codantastic

Backend Engineer in love with Full-Stack. Develops in Java | Spring Boot | Elixir | NodeJS | ExpressJS | React | Go https://portfolio.sahilpaudel.in