How to Crop Images in Node.js

To crop images in Node.js :

  1. Install the Sharp Module
  2. The installed module exposes the extract function. Use this to crop off a section of the image

Installing Sharp

npm install sharp --save

Using the extract Method

The extract method is used to crop images. This accepts 4 number parameters :

  • top : offset from the top edge of the image
  • left : offset from the left edge of the image
  • width : width of the extracted image
  • height : height of the extracted image
const sharp = require('sharp');

// original image
let originalImage = 'originalImage.jpg';

// file name for cropped image
let outputImage = 'croppedImage.jpg';

sharp(originalImage).extract({ width: 1920, height: 1080, left: 60, top: 40 }).toFile(outputImage)
    .then(function(new_file_info) {
        console.log("Image cropped and saved");
    })
    .catch(function(err) {
        console.log("An error occured");
    });

It is important to note that all parameters must be present or an error will be thrown.

Resizing Images in Node.js