images-watermark
v1.2.0
Published
π A powerful, fast, and user-friendly Node.js library for adding professional watermarks to images. Protect your content with text watermarks, logo overlays, or both! Built with Sharp for lightning-fast processing, featuring intelligent caching, flexible
Maintainers
Keywords
Readme
πΌοΈ Images Watermark
A powerful, fast, and user-friendly Node.js library for adding professional watermarks to images. Protect your content with text watermarks, logo overlays, or both!
π π Full Documentation - Complete guides, API reference, and examples
β¨ Features
- π― Text Watermarks - Add custom text with full styling control
- πΌοΈ Image Watermarks - Overlay logos or images as watermarks
- π Combined Watermarks - Use both text and image watermarks simultaneously
- β‘ High Performance - Built with Sharp for lightning-fast processing
- π¨ Customizable - Control position, size, opacity, colors, and fonts
- π Security - Referrer-based access control for protected content
- πΎ Intelligent Caching - Automatic caching for improved performance
- π± Multiple Formats - Support for PNG, JPEG, WebP, and more
- π Batch Processing - Process multiple images at once
- ποΈ Flexible Positioning - 9 different watermark positions
- π Comprehensive Documentation - Full JSDoc comments and examples
π Quick Start
Installation
npm install images-watermarkBasic Usage
const Watermark = require('images-watermark');
// Single image watermark
const watermarkedImage = await Watermark.singleImageWatermark({
imagePath: './path/to/image.jpg',
textWatermark: 'My Brand',
allowedReferrers: ['https://mywebsite.com'],
headers: { referer: 'https://mywebsite.com' }
});
// Multiple images watermark
const watermarkedImages = await Watermark.multiImageWatermark({
imagePaths: ['./image1.jpg', './image2.jpg'],
watermarkPath: './logo.png',
allowedReferrers: ['https://mywebsite.com'],
headers: { referer: 'https://mywebsite.com' }
});π API Reference
Watermark.singleImageWatermark(options)
Add watermark to a single image.
Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| imagePath | string | β
| - | Path to the source image |
| allowedReferrers | string[] | β
| - | Array of allowed referrer domains |
| headers | object | β
| - | Request headers for access control |
| watermarkPath | string | β | - | Path to watermark image (logo) |
| textWatermark | string | β | - | Text to use as watermark |
| appName | string | β | - | App name (alternative to textWatermark) |
| textColor | string | β | 'black' | Text color |
| opacity | string | β | '0.3' | Text opacity (0.0-1.0) |
| fontWeight | string | β | '800' | Font weight |
| textLineSpacing | string | β | '5' | Line spacing multiplier |
| fontFamily | string | β | 'Inter, Arial, sans-serif' | Font family |
Returns
Promise<Buffer>- Watermarked image bufferPromise<string>- Original image path (if access denied)
Watermark.multiImageWatermark(options)
Add watermark to multiple images in parallel.
Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| imagePaths | string[] | β
| - | Array of image paths |
| allowedReferrers | string[] | β
| - | Array of allowed referrer domains |
| headers | object | β
| - | Request headers for access control |
| watermarkPath | string | β | - | Path to watermark image (logo) |
| textWatermark | string | β | - | Text to use as watermark |
| appName | string | β | - | App name (alternative to textWatermark) |
| textColor | string | β | 'black' | Text color |
| opacity | string | β | '0.3' | Text opacity (0.0-1.0) |
| fontWeight | string | β | '800' | Font weight |
| textLineSpacing | string | β | '5' | Line spacing multiplier |
| fontFamily | string | β | 'Inter, Arial, sans-serif' | Font family |
Returns
Promise<Buffer[]>- Array of watermarked image buffersPromise<string[]>- Array of original image paths (if access denied)
Utility Methods
Watermark.clearCache()
Clear the internal watermark cache.
Watermark.getCacheStats()
Get cache statistics (hits, misses, keys, etc.).
π― Examples
1. Text Watermark Only
const Watermark = require('images-watermark');
const watermarkedImage = await Watermark.singleImageWatermark({
imagePath: './photos/landscape.jpg',
textWatermark: 'Β© 2024 My Company',
textColor: '#FF0000',
opacity: '0.5',
fontWeight: 'bold',
allowedReferrers: ['https://mywebsite.com'],
headers: {
referer: 'https://mywebsite.com',
'user-agent': 'Mozilla/5.0...'
}
});2. Image Watermark Only
const Watermark = require('images-watermark');
const watermarkedImage = await Watermark.singleImageWatermark({
imagePath: './photos/portrait.jpg',
watermarkPath: './assets/logo.png',
allowedReferrers: ['https://mywebsite.com'],
headers: {
referer: 'https://mywebsite.com',
'user-agent': 'Mozilla/5.0...'
}
});3. Combined Text and Image Watermark
const Watermark = require('images-watermark');
const watermarkedImage = await Watermark.singleImageWatermark({
imagePath: './photos/product.jpg',
watermarkPath: './assets/brand-logo.png',
textWatermark: 'PROTECTED CONTENT',
textColor: '#FFFFFF',
opacity: '0.7',
fontWeight: '900',
fontFamily: 'Arial, sans-serif',
allowedReferrers: ['https://mywebsite.com'],
headers: {
referer: 'https://mywebsite.com',
'user-agent': 'Mozilla/5.0...'
}
});4. Batch Processing
const Watermark = require('images-watermark');
const imagePaths = [
'./photos/image1.jpg',
'./photos/image2.jpg',
'./photos/image3.jpg'
];
const watermarkedImages = await Watermark.multiImageWatermark({
imagePaths,
appName: 'My Brand',
textColor: '#000000',
opacity: '0.3',
allowedReferrers: ['https://mywebsite.com'],
headers: {
referer: 'https://mywebsite.com',
'user-agent': 'Mozilla/5.0...'
}
});5. Express.js Integration
const express = require('express');
const Watermark = require('images-watermark');
const path = require('path');
const app = express();
app.get('/watermark/:imageName', async (req, res) => {
try {
const imagePath = path.join(__dirname, 'images', req.params.imageName);
const watermarkedImage = await Watermark.singleImageWatermark({
imagePath,
textWatermark: 'Β© 2024 My Website',
allowedReferrers: ['https://mywebsite.com'],
headers: req.headers
});
res.setHeader('Content-Type', 'image/png');
res.send(watermarkedImage);
} catch (error) {
console.error('Watermark error:', error);
res.status(500).send('Error processing image');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});6. Cache Management
const Watermark = require('images-watermark');
// Get cache statistics
const stats = Watermark.getCacheStats();
console.log('Cache hits:', stats.hits);
console.log('Cache misses:', stats.misses);
// Clear cache if needed
Watermark.clearCache();π Security & Access Control
The library uses referrer-based access control to protect your images:
- Allowed Referrers: Specify domains that can access images without watermarks
- Headers Validation: Uses request headers to determine access permissions
- Cookie Check: Validates if user has proper authentication
- User-Agent Filtering: Prevents automated access from certain user agents
Access Control Logic
// Access is granted if:
// 1. User has valid cookies
// 2. User-Agent is not 'undici' (prevents automated access)
// 3. Referrer is NOT in allowed list (forces watermark for external access)
const isDirectAccess = headers['user-agent'] !== 'undici' &&
!isValidReferrer &&
headers.cookie;π¨ Customization Options
Text Watermark Styling
- Color: Any valid CSS color (
#FF0000,red,rgb(255,0,0)) - Opacity: 0.0 to 1.0 (transparent to opaque)
- Font Weight: CSS font-weight values (
normal,bold,100-900) - Font Family: Any installed font family
- Line Spacing: Multiplier for line spacing
Watermark Positioning
- Text Watermarks: Centered on the image
- Image Watermarks: Southeast corner (bottom-right)
- Combined: Text centered, image in southeast corner
β‘ Performance Features
- Intelligent Caching: SVG watermarks are cached for 24 hours
- Parallel Processing: Multiple images processed simultaneously
- Memory Efficient: Uses Sharp for optimized image processing
- Async Operations: Non-blocking image processing
π οΈ Requirements
- Node.js >= 20.0.0
- Sharp (automatically installed)
- Node-cache (automatically installed)
π License
MIT License - see LICENSE file for details.
π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
π Author Details
β Star this repository if you find it helpful!
