DEV Community

Pankaj Kumar
Pankaj Kumar

Posted on

How to Resize Image in NodeJS

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).

Click here to get complete working code.

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"
Enter fullscreen mode Exit fullscreen mode

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 = [
300 + 'x' + 300,

im.convert(convertArgs, function(err, metadata){
if (err) throw err;

console.log('success! Checkout your new thumb: ');
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)