27 Aug 2013

Resize an Image using ImageMagick and node.js

A simple example showing how to resize an image using the imagemagick module.

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 server = http.createServer(function(req, res) {

  var options = {
    width: 120,
    height: 80,
    srcPath: "image.png",
    dstPath: "output.png"
  };

  im.resize(options, function(err) {
    if(err) { throw err; }
    res.end("Image resize complete");
  });

}).listen(8080);

We use the resize convenience function, which accepts an object as its first parameter. The object's properties define the input image path, output image's width, height and destination path.

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

Example image

Start:

$ node server.js

Invoke using your browser:

http://localhost:8080
Image resize complete

Check the resulting image is the correct size:

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

Output.png:

Resized image