Last Updated: September 09, 2019
·
5.212K
· vvo

Image batch resize in node.js

This handy resize module will not kill your server, thanks to async's queue.
At max it will fork .cpus().length image magick processes.

var
  async = require('async'),
  fs = require('fs'),
  im = require('imagemagick'),
  maxworkers = require('os').cpus().length,
  path = require('path');

module.exports = resize;

function resize(params) {
  var queue = async.queue(resizeimg, maxworkers);

  fs.readdir(params.src, function(err, files) {
    files.forEach(function(file) {
      queue.push({
        src: path.join(params.src, '/', file),
        dest: path.join(params.dest, '/', file),
        width: params.width,
        height: params.height
      })
    });
  });
}

function resizeimg(params, cb) {
  var imoptions = {
    srcPath: params.src,
    dstPath: params.dest
  };
  if (params.width !== undefined) imoptions.width = params.width;
  if (params.height !== undefined) imoptions.height = params.height
  im.resize(imoptions, cb);
}

Usage:

resize({
  src: '/source/folder',
  dest: '/destination/folder',
  width: 300
});

You can provide only width or only height or both.

2 Responses
Add your response

Looks nice / useful! Thx

over 1 year ago ·

Why we need to use async.queue instead forEach or maybe map?

Thanks

over 1 year ago ·