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.
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.
- Express 4
- imagemagick
I have created a package.json file that will install all required dependencies.
{
"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
Let’s start with Directory Structure, 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. In initialize we have used express app to perform get operations and also requires the imagemagick module. Now will get all the information about image like height, width, resolution etc. See below code to get image information, In above code you can see in get request we are calling im.identify to get basic information about images. Now will fetch specific information about images like for height, please see below code. 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. Using this we can access metadata for the images. like dateTime, orientation etc. 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. 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. 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. For image conversion, we can convert image from one format to another with its new height and width. 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. 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. 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, 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. 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. Meet Mukul, a passionate visionary and a dedicated 3D printing enthusiast. With an insatiable curiosity for technology and a flair for creativity, Mukul has discovered a world where innovation knows no bounds. Armed with a deep understanding of 3D printing and its endless possibilities, he has become a true pioneer in the field, constantly pushing the boundaries of what can be achieved with this remarkable technology.Directory Structure
source_images
destination_images
index.js
package.json
Also we have used Express to create routes to perform different operations.
So, let’s start with code.Initialize and requires
var express = require('express');
app = express(),
fs = require('fs'),
im = require('imagemagick'),
srcImage = "source_images/butterfly.jpg",
desPath = "destination_images/";
Image Information
app.get('/getimage/information', function(req, res) {
im.identify(srcImage, function(err, features){
if (err) throw err;
res.json({"images_data": features});
});
});
So by calling im.identify will give us information about image.Specific Image Information
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});
});
});
Read Metadata
app.get('/getimage/readmetadata', function(req, res) {
im.readMetadata(srcImage, function(err, metadata){
if (err) throw err;
res.json({"metadata": metadata});
});
});
Image Resize
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: []
}
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"
});
});
});
Image Convert
options for convert
['source image', '-resize', '25x120', 'destination image']
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"
});
});
});
Image Crop
options for crop
[NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast]
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"
});
});
});
Conclusion
Hi
I downloaded the file, and try to execute. But only http://localhost:8900 is working..
how to execute rest of the methods?
http://localhost:8900/getimage/information
crash and getting error
throw er; // Unhandled ‘error’ event
Hi,
It should work. everything is work fine for me. just make sure you are calling GET request while hitting that API.
Thanks.
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
^
Ignore, issue with local instance of ImageMagick.