Crop Images in Node.js
In this tutorial, you will see how to crop an image in Node.js. We will use sharp library to crop images. Sharp is an image processing library of Node.js that supports different image file formats like JPEG, PNG, GIF, WebP, AVIF, SVG, and TIFF.
Installation:
npm i sharp
Open your terminal write npm i sharp
like above and execute your command to install the sharp library.
const sharp = require('sharp'); let originalImage = 'sm.jpg'; let outputImage = 'output.jpg';
In the above program, sharp
to expose the extrac
t function which I have created in the program below.
Then the originalImage
is the path or name of the image file which I want to crop.
And the outputImage
is the path where the output file will be created.
sharp(originalImage) .extract({ width: 920, height: 580, left: 60, top: 40 }) .toFile(outputImage)
To crop the image we used extract
method. This method supports 4 parameters.
- width: to set the width of the photo area that needs to be cropped.
- height: to set the height of the photo area that needs to be cropped.
- left: to set the horizontal position of the photo area that needs to be cropped.
- top: to set the vertical position of the photo area that needs to be cropped.
Then the tofile()
method is passed to save the cropped image as output.jpg
.then(function(new_file_info) { console.log("Image cropped"); })
The above function will execute if there is no error taking place and print “Image cropped” through the console.log
.
.catch(function(err) { console.log("There is an error occurred"); });
If there is any kind of error taken place in the program, then the above function will execute and print “There is an error occurred” message through the console.log
.
Here’s the complete program below.
const sharp = require('sharp'); let originalImage = 'test.jpg'; let outputImage = 'output.jpg'; sharp(originalImage) .extract({ width: 1000, height: 1000, left: 60, top: 40 }) .toFile(outputImage) .then(function(new_file_info) { console.log("Image cropped"); }) .catch(function(err) { console.log("There is an error occurred"); });
To run the above program open the terminal and write there node
then your file name like below and execute your command.
PS G:\saM> node index.js
After you run the program you will get a file in your working directory that is output.jpg
and that’s the image we have cropped.
Can you explain me how to use Sharp in an e-commerce website while taking the image in the req.params format