Last active
April 16, 2017 10:05
-
-
Save zapkub/17e7d9111cef566b5c5a565a1c4c5843 to your computer and use it in GitHub Desktop.
node imagemagick batch resizing multithread
This file contains hidden or 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
// Batch image resizing with Node Imagemagick | |
// author: Rungsikorn Rungsikavanich | |
// contact: [email protected] | |
// Dependencies ( Need native imagemagick ) | |
// $ brew install imagemagick | |
// $ npm i imagemagick lodash | |
// example: `$ DIR=../static/images/stock/herbarium-original node ./lib/batch-resizer.js` | |
// result image will be locate in ./resize folder | |
const im = require('imagemagick'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const _ = require('lodash'); | |
// DIR is Relative from script location | |
const images = fs.readdirSync(path.join(__dirname, process.env.DIR || '.')); | |
// P is number of parallel threads | |
const threads = parseInt(process.env.P, 10) || 20; | |
const imagesList = images; | |
(async function () { | |
for (let index = 0; index < imagesList.length - 1; index += threads) { | |
console.log(`parallel resizing started at index: ${index}`); | |
const q = _.range(index, index + threads, 1) | |
.map(async (i) => { | |
const imageName = imagesList[i]; | |
try { | |
if (imageName) { | |
const imagePath = path.join(__dirname, process.env.DIR || '.', imageName); | |
const dstPath = path.join(__dirname, process.env.DIR || '.', 'resize', `${path.basename(imageName)}`); | |
const ext = path.extname(imageName); | |
if (ext.toLowerCase() === '.jpg') { | |
const resizePromise = new Promise((rs) => { | |
im.resize({ | |
srcPath: imagePath, | |
dstPath, | |
width: 1024, | |
}, () => { | |
console.log(`${i}/${images.length} (${imageName})`); | |
rs(); | |
}); | |
}); | |
await resizePromise; | |
} | |
} | |
} catch (e) { | |
console.log(`error${imageName}`); | |
console.log(e); | |
} | |
}); | |
await Promise.all(q); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment