How to Resize Image in NodeJS

Pankaj Kumar
2 min readOct 12, 2021

Hello, Today we will create a demo in Nodejs where the image will be resized of the required dimension. As we need to generate thumbnail images in the application where we think all aspects to improve the performance of the application. Very basic steps are needed to perform the task. In Nodejs application, it is very difficult to resize or compress the image while uploading with multer package(in case of uploading the 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

Article was originally posted over jsonworld.com

Click here to Join live Classed led by IT Professionals of Tech Giants like TCS, IBM, Accenture, Infosys, etc.

--

--

Pankaj Kumar

JavaScript Developer | Blogger — Expert in NodeJS, Firebase, Angular, React(Instructor at edhint.com)