Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Batch watermark images with GM
var Q = require('q');
var async = require('async');
var fs = require('fs');
var gm = require('gm');
var join = require('path').join;
var readdir = Q.denodeify(fs.readdir);
var dir = join(__dirname, 'images');
var dest = join(__dirname, 'dest');
var logo = join(__dirname, 'resources/tlf-logo-medium.png');
/**
* Watermark image on bottom right
*/
function compositeWatermark(file) {
var defered = Q.defer();
if (/jpg|jpeg|png|gif|bmp/.test(file)) {
gm(join(dir, file))
.composite(logo)
.gravity('South')
.geometry('+0+100')
.write(join(dest, file), function (err) {
if (err) {
console.log(err);
defered.reject(err);
} else {
console.log('Complete Composite', file);
defered.resolve();
}
});
} else {
console.log('Not an image', file);
defered.resolve();
}
return defered.promise;
}
function openDir(path) {
return readdir(path)
.then(function(files) {
async.eachSeries(files, function (file, callback) {
compositeWatermark(file).then(callback);
}, function (err) {
if (err) throw err;
console.log('Processing complete!');
process.exit(1);
});
});
}
// proxy fs.exists to return a promise. Example of Q.defer
function exists(file){
var deferred = Q.defer();
fs.exists(file, function(result){
return result ? deferred.resolve(file) : deferred.reject('invalid file');
});
return deferred.promise;
}
openDir(dir).done(function (err, data) {
if (err) throw err;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.