jxson
10/6/2011 - 6:03 AM

Crop images with node

Crop images with node

{
  "name": "node-crop-example",
  "version": "0.0.1",
  "dependencies": {
    "imagemagick": "0.1.2",
    "optimist": "0.2.6",
    "underscore": "1.2.0"
  }
}

var im = require('imagemagick')
  , path = require('path')
  , argv = require('optimist').argv
  , _ = require('underscore')
  , options
  , convertArgs
;

if (! argv._[0]){
  throw new Error([
    'You need to pass in the image to crop:',
    '   node crop.js image.jpg'
  ].join('\n'));
}

options = _.defaults(argv, {
    image: argv._[0]
  , width: '100'
  , height: '100'
  , destination: argv._[1] || 'thumb' + path.extname(argv._[0])
});

console.log('making a thumb of:', options.image);

convertArgs = [
  options.image,
  '-resize',
  options.width + 'x' + options.height,
  options.destination
];

im.convert(convertArgs, function(err, metadata){
  if (err) throw err;

  console.log('success! Checkout your new thumb: ' + options.destination);
});

node.js and imagemagick example

Simpler than I thought, you can convert images using this reference implementation:

node convert.js image.jpg thumb.jpg

You can also pass in arguments: --width, --height

For more details see:

https://github.com/rsms/node-imagemagick