26 Aug 2013

Crop an Image using ImageMagick and node.js

Crop an image using node.js and the imagemagick node module. The module's convert method is used, where native ImageMagick arguments are passed in as an array. Size, offset and an input image path are supplied to produce a cropped output PNG, which is written to file.

Install the ImageMagick module using npm:

$ npm install imagemagick

Assert ImageMagick is installed:

$ convert --version
Version: ImageMagick 6.6.0-4 2012-08-17 Q16
Copyright: Copyright (C) 1999-2010 ImageMagick
Features: OpenMP

If required, install ImageMagick:

$ sudo apt-get install imagemagick

server.js:

var http = require("http");
var im = require("imagemagick"); 

var args = [
  "image.png",
  "-crop",
  "120x80+30+15",
  "output.png"
];

var server = http.createServer(function(req, res) {

  im.convert(args, function(err) {
    if(err) { throw err; }
    res.end("Image crop complete");
  });

}).listen(8080);

We use the convert method, which accepts an array of arguments. In this case: input image path, convert type, crop metrics and output image path.

The image paths are relative to the working directory.

Save this image (or any image named image.png) in the working directory:

Example image

Start the server:

$ node server.js

Invoke using your browser:

http://localhost:8080
Image crop complete

Check the output image's size is correct:

$ identify -format %wx%h output.png
120x80

Output.png should look like this:

Cropped image

The crop region begins 30 pixels from the left and 15 pixels from the top of the original image, as specified in the arguments.

Under the hood the imagemagick module simply executes the ImageMagick's convert command by spawning a child process, where any supplied arguments are passed through. The command line equivalent is: convert image.png -crop 120x80+30+15 output.png

Although less versatile, the crop convenience function can also be used.