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


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

var args = [

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

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


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:

Image crop complete

Check the output image's size is correct:

$ identify -format %wx%h output.png

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.