Open In App

Node Jimp | scaleToFit

Improve
Improve
Like Article
Like
Save
Share
Report

The scaleToFit() function is an inbuilt function in Nodejs | Jimp that scales the image to the largest size that fits inside the rectangle that has the given width and height.

Syntax: 

scaleToFit(w, h, mode, cb)

Parameter: 

  • w: This parameter stores the width of the image.
  • h: This parameter stores the height of the image.
  • mode:  This is an optional parameter that stores the scaling method.
  • cb: This is an optional parameter that is invoked when compilation is complete.

Input Images: 

Setup Environment : 

npm init -y

Install Dependencies :

npm install jimp 

Example 1:  In this example, we will see the use of scaleToFit().

javascript




// npm install --save jimp
// import jimp library to the environment
const Jimp = require('jimp');
 
// User-Defined Function to read the images
async function main() {
    const image = await Jimp.read('
        // scaleToFit Function having width and height
        image.scaleToFit(300, 300)
            .write('scaleToFit1.png');
}
 
main();
console.log('Image Processing Completed');


Output: 


Example 2: With mode and cb (optional parameters) 

javascript




// npm install --save jimp
// import jimp library to the environment
const Jimp = require('jimp');
 
// User-Defined Function to read the images
async function main() {
    const image = await Jimp.read('
        // scaleToFit Function having width, height, mode and callback function
        image.scaleToFit(1000, 1700, Jimp.RESIZE_BEZIER, function (err) {
            if (err) throw err;
        })
            .write('scaleToFit2.png');
}
 
main();
console.log('Image Processing Completed');


Output: 


Reference: https://www.npmjs.com/package/jimp



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads