How to crop an image using crop() function in Node Jimp?


NodeJS – Crop() is an inbuilt function that is used to crop the images. We can use crop to select/crop an image within specified coordinates and dimnesions.

Syntax

crop( x, y, w, h, cb )

Definition of crop() paramters

  • x – It will hold the value of x co-ordinate of cropping. (Required)

  • y – It will hold the value of y co-ordinate of cropping. (Required)

  • w – This parameter is used to store the width of the cropping image. (Required)

  • h – This parameter is used to store the height of the cropping image. (Required)

  • cb – This is an optional parameter that can be invoked after the compilation is complete.

Input Image

Using Node JIMP – CROP()

Before proceeding to use crop() functions, please check that the following statements are already executed for setting up the environment.

  • npm init -y // Initialising the Node environment

  • npm install jimp --save // Installing the jimp dependency

  • Create a crop.js file and copy-paste the following code snippet in it.

  • Use node crop.js to run the code.

Note − The method name should match with the JS file name. Only then it will be able to call the desired method.

Example

const Jimp = require('jimp') ;

async function crop() { // Function name is same as of file name
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.crop(100, 50, 470, 270)
   .write('/home/jimp/crop.jpg');
}

crop(); // Calling the function here using async
console.log("Image is processed successfully");

Output

Using Node JIMP – CROP() with 'cb' optional parameters

Example

const Jimp = require('jimp') ;

async function crop() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   // Checking if any error occurs while cropping
   image.crop(150, 0, 1000, 1800, function(err){
      if (err) throw err;
   })
   .write('/home/jimp/crop.jpg');
}

crop();
console.log("Image is processed successfully");

Output

/home/jimp/ >> node crop.js // On running the above code snippet
Image is processed successfully
(node:194779) UnhandledPromiseRejectionWarning: RangeError [ERR_OUT_OF_RANGE]:
The value of "offset" is out of range. It must be >= 0 and <= 1119996.
Received 1120040
   at boundsError (internal/buffer.js:49:9)
   at Buffer.readUInt32BE (internal/buffer.js:192:5)
   at Jimp.<anonymous> (/home/jimp/node_modules/@jimp/plugincrop/dist/index.js:43:37)
   at scan (/home/jimp/node_modules/@jimp/utils/dist/index.js:53:9)
   at Jimp.scanQuiet
(/home/jimp/node_modules/@jimp/core/dist/index.js:1262:32)
   at Jimp.cropQuiet (/home/jimp/node_modules/@jimp/plugincrop/dist/index.js:42:12)

Updated on: 27-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements