How to resize images using Node.js

Last updated on June 10, 2020 A Goodman Loading... Post a comment

Resizing images in Node.js is super easy with a library named gm. To use this one, you need to install ImageMagick first. Here is the download page for Windows, Linux, and macOS.

After installing ImageMagick, open your terminal and execute the following command to ensure everything is OK:

magick --version

You should see something similar to this:

Version: ImageMagick 7.0.10-17 Q16 x86_64 2020-06-07 https://imagemagick.org
Copyright: © 1999-2020 ImageMagick Studio LLC
License: https://imagemagick.org/script/license.php
Features: Cipher DPC HDRI Modules OpenMP(3.1) 
Delegates (built-in): bzlib freetype gslib heic jng jp2 jpeg lcms lqr ltdl lzma openexr png ps tiff webp xml zlib

Using gm with Node.js

Official docs: https://github.com/aheckmann/gm

Installation:

npm install gm --save

Sample code:

const gm = require("gm");

/*
input: the path to the image your want to resize
output: the path to the image created by the resizing process
width, height: the dimension of the output image
*/
const resizeImage = (input, output, width, height) => {
  gm(input)
    .resize(width, height)
    .write(output, (err) => {
        if(err){
            console.log(err);
        } else {
            console.log('Done');
        }
    });
};

// Testing 
resizeImage('a.jpg', 'a-resized.jpg', 300, 200);
// Don't forget to use put an image named 'a.jpg' in your project directory

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x