/** * Make sure you have imagemagich installed on your system */ const im = require('imagemagick'); const g = require('glob'); /** * Find all files with a specific pattern * * @param {String} pattern */ async function glob(pattern) { return new Promise((resolve, reject) => { g(pattern, (err, files) => { if(err) return reject(err); return resolve(files); }) }) } /** * Crop a specific image with arguments * * @param {String} img * @param {Object} args */ async function crop(img, args) { // By default I tag images that require resizing with "_tmp", you can change this to whatever you want const dstPath = img.replace('_tmp', ''); const options = Object.assign({ srcPath: img, dstPath, gravity: 'Center' }, args); return new Promise((resolve, reject) => { im.crop(options, (err, stdout, stderr) => { if(err) return reject(err); return resolve(); }); }); } /** * Crop all images in a directory * * @param {String} dir * @param {Object} args */ async function cropImages(dir, args) { const files = await glob(dir); await Promise.all(files.map(async (file) => { await crop(file, args); })); } async function run() { try { await cropImages('foo/some/dir/**/*_tmp.jpg', { width: 300, height: 300 }); await cropImages('some/other/dir/**/*_tmp.jpg', { width: 380, height: 250 }); } catch(err) { console.error(err); } } run();