How to Resize Image in NodeJS

    Apr 25, 2017       by Pankaj Kumar
Resize-image-nodejsapp.jpg

Hello, Today we will create a demo in nodejs where image will be resize of the required dimension. As we need to generate thumbnail images in the application where we think all aspect to improve the performace of the application. A very basic steps are needed to perform the task. In nodejs applicationi it is verydifficult to resize or compress the image while uploading with multer package(in case of uploading file to our own server).

 

Package required

For the image compression task we will use imagemagick package of nodejs. So at first we have to install imagemagick in our system, I am using linux with ubuntu. sudo apt-get install imagemagick will install the software in our system.

 

Now create a file named server.js and create a basic app of nodejs. I am not adding much thing here in the demo to clear the actual concept for image compression task in nodejs application. So I have written very basic code in my demo. Lets have a look in code of my package.json.

 

 
{
    "name": "node-resize-example",
    "version": "1.0.0",
    "dependencies": {
       "imagemagick": "0.1.2"
   }
}

 

In the above file we can see that only one npm package has been installed.

Now move to the next file, server.js. Lets have a look inside it.

 

 
var im = require('imagemagick')
, path = require('path')
 
let convertArgs = [
'./images/tes.jpg',
'-resize',
300 + 'x' + 300,
'./images/thumbnail_test.jpg'
];
 
im.convert(convertArgs, function(err, metadata){
if (err) throw err;
 
console.log('success! Checkout your new thumb: ');
});

 

In the above file at top we have required the node packages. below that we have created a variable named convertArgs having first value as the current image second and value as the required size of thumbnail/resized images and last value as the name of the new file. At the end we call the convert method of imagemagick which  is performing the actual task. By following these easy steps we can compress/resize image in our nodejs app.

For more info visit its official site : Click here to redirect

 

That’s all for now. Thank you for reading and I hope this post will be very helpful for image compression in nodejs app.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

Find complete source code over GitHub


WHAT'S NEW

Find other similar Articles here: