Last active
October 12, 2017 02:04
-
-
Save woutrbe/4a762b3356fc668967f177bcb7fe4f54 to your computer and use it in GitHub Desktop.
Quickly resize and crop images in Node.js
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
/** | |
* 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment