Image manipulation using NodeJS and ImageMagick

December 21, 2015
by Inaam Hussain

In this tutorial we will learn how we can minify images, corp images, convert images, etc. by implementing image manipulation in NodeJS using ImageMagick.
 
If you have a web application or website which runs on NodeJS and you have to show the list of images. In which images size is in MB’s, So it will take time to load web application and slow down your app.

Using imagemagick node module we can lower down quality or any other factors which will help our webApp to load fast using this we can reduce the image size considerably from MB’s to KB’s.

DOWNLOAD

Prerequisites

For creating image manipulation app you need following things.

  • Computer running with either MAC, Windows or Linux.
  • Node.js (Download)

Install dependencies

We are going to use following node modules for manipulating images.

  1. Express 4
  2. imagemagick

I have created a package.json file that will install all required dependencies.

package.json
{
  "name": "image manipulation",
  "version": "1.0.0",
  "description": "image manipulation",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "inaam husain",
  "license": "MIT",
  "dependencies": {
    "express": "^4.13.3",
    "imagemagick": "^0.1.3"
  }
}

How to install dependencies?

Add the above package.json into your project folder and run the below command in command prompt.

npm install

Getting started

Let’s start with Directory Structure,

Directory Structure

Directory Structure
    source_images
    destination_images
    index.js
    package.json

In above directory you can see that we have two folders in which the source_images folder contains our real images and destination_images folder contain our manipulated images and index.js is holding our app code.
Also we have used Express to create routes to perform different operations.
So, let’s start with code.

Initialize and requires

index.js
var express = require('express');
        app = express(),
        fs = require('fs'),
        im = require('imagemagick'),
        srcImage = "source_images/butterfly.jpg",
        desPath = "destination_images/";

In initialize we have used express app to perform get operations and also requires the imagemagick module.

Image Information

Syntax : im.identify(srcImageLocation, callbackFunction(err,output))

Now will get all the information about image like height, width, resolution etc. See below code to get image information,

index.js
app.get('/getimage/information', function(req, res) {
    im.identify(srcImage, function(err, features){
        if (err) throw err;
        res.json({"images_data": features});
    });
});

In above code you can see in get request we are calling im.identify to get basic information about images.
So by calling im.identify will give us information about image.

Specific Image Information

Syntax : im.identify(['-format','%w%h', srcImageLocation], callback(err,output))

Now will fetch specific information about images like for height, please see below code.

index.js
app.get('/getimage/information/:specific', function(req, res) {
    var selectSpecific = decodeURIComponent(req.params.specific);
    selectSpecific = JSON.parse(selectSpecific).join("%");
    im.identify(['-format','%'+selectSpecific, srcImage], function(err, output){
        if (err) throw err;
        res.json({"images_data": output});
    });
});

So using above code we can access specific information using same as im.identify function. in which first parameter specifies the operation -format and second is parameters and last one is image location.

Read Metadata

Syntax : im.identify(['-format','%w%h', srcImageLocation], callback(err,output))

Using this we can access metadata for the images. like dateTime, orientation etc.

index.js
app.get('/getimage/readmetadata', function(req, res) {
    im.readMetadata(srcImage, function(err, metadata){
        if (err) throw err;
        res.json({"metadata": metadata});
    });
});

Using im.readMetadata function we can access metadata information about images in which we just need to pass the image location and in callback you will get the information about it.

Image Resize

Syntax : im.resize(optionsObj, callback(err, stdout))

For image re-size, we can re-size image in terms of height, width, quality etc. in which options you can pass following parameter to perform particular operation.

options for resize

{
    srcPath: undefined,
    srcData: null,
    srcFormat: null,
    dstPath: undefined,
    quality: 0.8,
    format: 'jpg',
    progressive: false,
    width: 0,
    height: 0,
    strip: true,
    filter: 'Lagrange',
    sharpening: 0.2,
    customArgs: []
}
index.js
app.get('/image/resize', function(req, res) {
    var optionsObj = {
        srcPath: srcImage,
        dstPath: desPath+"butterfly_lowquality.jpg",
        quality: 0.6,
        width: ""
    };
    im.resize(optionsObj, function(err, stdout){
        if (err) throw err;
        res.json({
            "message": "Resized Image successfully"
        });
    });
});

Using im.resize function we can easily perform operation like resize and quality change of images. In options we need to specify source image path and destination image path and width of it. So these three thing is must before running this function. In this example I have changed the size of image which is earlier 6.34MB and after applying resize with it’s quality (i.e:- quality: 0.6) it get converted to 897kb.

Image Convert

Syntax : im.convert(optionsArray, callback(err, stdout))

For image conversion, we can convert image from one format to another with its new height and width.

options for convert

['source image', '-resize', '25x120', 'destination image']
index.js
app.get('/image/convert', function(req, res) {
    var optionsObj = [srcImage, '-resize', '250x250', desPath+'butterfly_small.png'];
    im.convert(optionsObj, function(err, stdout){
        if (err) throw err;
        res.json({
            "message": "Converted Image successfully"
        });
    });
});

Using im.convert we can easily convert one image to another.in which first array value is source path, second is operation field that is resize and third is heightxwidth and last is destination image path. In this example we have converted image format jpeg to png with 250×250 it’s new height and width.

Image Crop

Syntax : im.crop(optionsObj, callback(err, stdout))

For image crop, we can crop images by it’s height and width. With it’s gravity from where you want to crop the image.

options for crop

All options are same as re-size except one new thing which is gravity, in gravity you can pass following one of the following options,

[NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast]
index.js
app.get('/image/crop', function(req, res) {
    var optionsObj = {
        srcPath: srcImage,
        dstPath: desPath+'butterfly_cropped.jpg',
        width: 800,
        height: 600,
        quality: 1,
        gravity: "North"
    };
    im.crop(optionsObj, function(err, stdout){
        if (err) throw err;
        res.json({
            "message": "cropped Image successfully"
        });
    });
});

Using im.crop function we can cut the image from where we need to crop using gravity options. In this example we have crop the image with height, width and gravity.

Conclusion

Using different tools of imagemagick we can easily perform image manipulation like get image information, get metadata info, resize image, convert image, crop image etc. Which will help us to load our app faster if you want to many images on one page.
 

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

4 comments

    • |

      Hi,

      It should work. everything is work fine for me. just make sure you are calling GET request while hitting that API.
      Thanks.

  1. |

    Getting the same error. What version of Node should I be using? I’m currently using v6.3.0

    connected to port 8900
    events.js:160
    throw er; // Unhandled ‘error’ event
    ^

  2. |

    Ignore, issue with local instance of ImageMagick.

Leave a Comment