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

Node.jsServer Side ProgrammingProgramming

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.

## 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
('/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");

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

### Example

const Jimp = require('jimp') ;

async function crop() {
('/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.
at Jimp.cropQuiet (/home/jimp/node_modules/@jimp/plugincrop/dist/index.js:42:12)