-
Notifications
You must be signed in to change notification settings - Fork 33
/
watermark.js
280 lines (232 loc) · 8.77 KB
/
watermark.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
*
* A powerful watermark library
* based on ImageMagick for node.js
*
**/
// System Imports
var fs = require('fs'),
im = require('imagemagick'),
path = require('path'),
ratify = require('node-ratify');
var defaultOptions = {
'text' : 'Sample watermark',
'override-image' : false,
'change-format' : false,
'output-format' : 'jpg',
'position' : 'Center',
'color' : 'rgba(0,0,0,0.4)',
'resize' : '100%'
}
//
// Check if the alignment passed
// is a valid alignment value
//
// Possible values of align are : dia1, dia2, ttb, btt, ltr, rtl
//
function _isValidAlignment(align) {
if (ratify.isEmpty(align))
return false;
//
// dia1 : Diagonal 1
// dia2 : Diagonal 2
// ttb : top to bottom
// btt : bottom to top
// ltr : left to right
// rtl : right to left
//
if (['dia1', 'dia2', 'ttb', 'btt', 'ltr', 'rtl'].indexOf(align.toLowerCase()) > -1)
return true;
return false;
}
function _isValidPosition(position) {
if (ratify.isEmpty(position))
return false;
if (['NorthWest', 'North', 'NorthEast', 'West', 'Center', 'East',
'SouthWest', 'South', 'SouthEast'].indexOf(position) > -1)
return true;
return false;
}
function _parseOptions(imageData, source, options) {
var retObj = {};
var width = imageData.width;
var height = imageData.height;
var fillColor = options.color;
var watermarkText = options.text;
var align = _isValidAlignment(options.align) ? options.align.toLowerCase() : 'dia1';
var font = options.font;
var resize = options.resize ? options.resize : defaultOptions.resize;
var outputPath = options.dstPath ? options.dstPath :
path.dirname(source) + '/watermark' + path.extname(source);
var position = _isValidPosition(options.position) ? options.position : 'Center';
var angle = null,
pointsize = null;
// Check if fillColor is specified
if (ratify.isEmpty(fillColor))
fillColor = defaultOptions.color;
// Check if watermark text is specified
if (ratify.isEmpty(watermarkText))
watermarkText = defaultOptions.text;
// Check if position is specified
if (ratify.isEmpty(position))
position = defaultOptions.position;
// Check if image needs to be overriden
if (options['override-image'] && ratify.isBoolean(options['override-image'])
&& options['override-image'].toString() === 'true') {
outputPath = source;
}
// Check if output format needs to be changed
if (options['change-format'] && ratify.isBoolean(options['change-format']) &&
options['change-format'].toString() === 'true') {
var outputFormat = options['output-format'];
if (ratify.isEmpty(outputFormat) || outputFormat.length < 2)
outputFormat = path.extname(source).substr(1);
outputPath = path.dirname(outputPath) + '/' +
path.basename(outputPath, path.extname(outputPath)) +
'.' + outputFormat;
}
// Check if extension of output path is valid
if (outputPath) {
var ext = path.extname(outputPath).substr(1);
if (!ext || ext.length < 2)
outputPath = path.dirname(outputPath) + '/' +
path.basename(outputPath, path.extname(outputPath)) +
path.extname(source);
}
var pointWidth = width,
pointHeight = height;
if (resize.toString().indexOf('%') == -1) {
resize = defaultOptions.resize;
} else {
var resizeFactor = (parseFloat(resize) / 100);
pointWidth = width * resizeFactor;
pointHeight = height * resizeFactor;
}
switch(align) {
case 'ltr' :
angle = 0;
pointsize = options.pointsize ? options.pointsize : (pointWidth / watermarkText.length);
break;
case 'rtl' :
angle = 180;
pointsize = options.pointsize ? options.pointsize : (pointWidth / watermarkText.length);
break;
case 'ttb' :
angle = 90;
pointsize = options.pointsize ? options.pointsize : (pointHeight / watermarkText.length);
break;
case 'btt' :
angle = 270;
pointsize = options.pointsize ? options.pointsize : (pointHeight / watermarkText.length);
break;
case 'dia1' :
angle = (Math.atan(height / width) * (180/Math.PI)) * -1;
pointsize = options.pointsize ? options.pointsize : Math.sqrt(pointWidth * pointWidth + pointHeight * pointHeight) / watermarkText.length;
break;
case 'dia2' :
angle = (Math.atan(height / width) * (180/Math.PI));
var pointsize = options.pointsize ? options.pointsize : Math.sqrt(pointWidth * pointWidth + pointHeight * pointHeight) / watermarkText.length;
break;
default :
angle = (Math.atan(height / width) * (180/Math.PI)) * -1;
pointsize = options.pointsize ? options.pointsize : Math.sqrt(pointWidth * pointWidth + pointHeight * pointHeight) / watermarkText.length;
break;
}
var args = [];
args.push(source); // original img path
args.push('-size');
args.push(width + 'x' + height);
args.push('-resize');
args.push(resize);
if (!ratify.isEmpty(font)) {
args.push('-font');
args.push(font);
}
args.push('-fill');
args.push(fillColor); // color of watermark text
args.push('-pointsize');
args.push(pointsize); // this needs to be calculated dynamically based on image size and length of copyright message
args.push('-gravity');
args.push(position); // alignment of watermark text.
args.push('-annotate');
args.push(angle); // angle of watermark message, with respect to X-axis
args.push(watermarkText); // copyright text
args.push(outputPath); // img with embedded watermark
retObj.args = args;
retObj.outputPath = outputPath;
return retObj;
}
function embedWatermark(source, options) {
if (!source || source == '')
throw new Error('Image-Watermark::embedWatermark : Specified an invalid image source');
// Check if file exists at the specified path
stats = fs.lstatSync(source);
if (!stats.isFile())
throw new Error('Image-Watermark::embedWatermark : Image does not exists at : ' + source);
// If options are not properly specified, use default options
if (!options || typeof options !== 'object')
options = defaultOptions;
// If we reach here that means file exists
im.identify(source, function (err, imageData) {
if (err)
throw new Error('Image-Watermark::embedWatermark : Unable to process image file : ' + err);
var retObj = _parseOptions(imageData, source, options);
im.convert(retObj.args, function(err, stdout) {
if (err)
console.log('Image-Watermark::embedWatermark : Error in applying watermark : ' + err);
else
console.log('Image-Watermark::embedWatermark : Successfully applied watermark. Please check it at :\n ' + retObj.outputPath);
});
});
}
function embedWatermarkWithCb(source, options, callback) {
var error;
if ((arguments.length < 2) ||
(arguments.length === 2 && !ratify.isFunction(arguments[1])) ||
(arguments.length > 2 && !ratify.isFunction(arguments[2]))) {
throw new Error('Image-Watermark::embedWatermarkWithCb : Invalid arguments to method embedWatermarkWithCb');
} else if (arguments.length === 2 && ratify.isFunction(arguments[1])) {
callback = arguments[1];
options = null;
}
if (!source || source == '') {
error = new Error('Image-Watermark::embedWatermarkWithCb : Specified an invalid image source');
return callback(error);
}
// Check if file exists at the specified path
fs.lstat(source, function(err, stats) {
if (err || !stats.isFile()) {
error = new Error('Image-Watermark::embedWatermarkWithCb : Image file doesn\'t exists at ' + source);
return callback(error);
} else if (!err) {
// If options are not properly specified, use default options
if (!options || typeof options !== 'object')
options = defaultOptions;
// If we reach here that means file exists
im.identify(source, function (err, imageData) {
if (err) {
error = new Error('Image-Watermark::embedWatermarkWithCb : Unable to process image file : ' + err);
return callback(error);
}
var retObj = _parseOptions(imageData, source, options);
im.convert(retObj.args, function(err, stdout) {
if (err) {
error = new Error('Image-Watermark::embedWatermarkWithCb : Error in applying watermark : ' + err);
return callback(error);
} else {
console.log('Image-Watermark::embedWatermarkWithCb : Successfully applied watermark. Please check it at :\n ' + retObj.outputPath);
return callback(null);
}
});
});
}
});
return;
}
exports = module.exports = {
embedWatermark : embedWatermark,
embedWatermarkWithCb : embedWatermarkWithCb,
version : JSON.parse(
require('fs').readFileSync(__dirname + '/package.json', 'utf8')
).version
};