Created
May 3, 2016 17:29
-
-
Save hamishhossack/9b0f3cec7a298ca34c5e459f11a2c628 to your computer and use it in GitHub Desktop.
Batch watermark images with GM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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