Adding and Resizing a Watermark on an Image Using Node.js with Sharp
Introduction
Watermarking images can be essential to protect your content or brand it effectively. In this post, I’ll show you how to add and resize a watermark on an image using Node.js with the powerful image-processing library, Sharp.
Prerequisites
Ensure you have Node.js installed and include Sharp in your project:
npm install sharp
Code Breakdown
Here’s the code we will be working with:
const sharp = require('sharp');
const inputImagePath = './backiee-290915-landscape.jpg'; // Path to the input image
const watermarkImagePath = './watermark.png'; // Path to the watermark image
const outputImagePath = './output-image.jpg'; // Path to the output image
// Load the input image to get its dimensions
sharp(inputImagePath)
.metadata()
.then(({ width }) => {
// Resize the watermark relative to the input image width (e.g., 10% of the input image width)
const watermarkWidth = Math.floor(width * 0.3); // Adjust the 0.1 to your preferred scale
return sharp(watermarkImagePath)
.resize(watermarkWidth) // Resize watermark
.toBuffer();
})
.then(watermarkBuffer => {
// Composite the watermark with the input image
return sharp(inputImagePath)
.composite([
{
input: watermarkBuffer,
gravity: 'southeast', // Position the watermark
blend: 'over', // Blending mode
}
])
.toFile(outputImagePath) // Save the output image with the resized watermark
.then(() => {
console.log('Watermark added and resized successfully!');
});
})
.catch(err => {
console.error('Error processing the image:', err);
});
Step-by-Step Explanation
- Load the input image: We start by loading the input image using
sharp(inputImagePath)
and getting its metadata, such as width. - Resize the watermark: We resize the watermark relative to the input image width. Here, we’re resizing it to 30% of the input image width by calculating
Math.floor(width * 0.3)
. - Composite the watermark: Using Sharp’s
composite()
method, we overlay the resized watermark onto the input image. We position the watermark in the bottom right corner using thegravity: 'southeast'
option. - Save the output: Finally, the composited image is saved to
outputImagePath
.
Customization
- Scale Adjustment: To change the watermark size relative to the input image, adjust the multiplier (e.g.,
0.1
for 10% or0.5
for 50%). - Watermark Positioning: You can change the position of the watermark by modifying the
gravity
property. Some common values: northwest
: top-leftnortheast
: top-rightsoutheast
: bottom-right (as used in our example)southwest
: bottom-left
Conclusion
In this guide, you’ve learned how to add a watermark to an image, scale it according to the input image, and position it using Sharp. This method is efficient and highly customizable for various use cases.