How to resize an image in Node.js
To resize an image we will use `sharp` package:
npm install sharp --save
Sharp provide the function `resize
` which accept height and/or width as argument.
If only height or width is provided then the other will be set accordingly to the aspect ratio.
const sharp = require('sharp');
let inputFile = "input_image.jpg";
let outputFile = "output_image.jpg";
let options = {
height: 800,
//width: 1200,
}
sharp(inputFile).resize(options).toFile(outputFile)
.then(function(createdFileInfo) {
console.log("Image resized successfully", createdFileInfo)
})
.catch(function(err) {
console.log("Error resizing the image", err);
});
here is a simple middleware for resizing uploaded image
exports.resizeUserPhoto = async (req, res, next) => {
if (!req.file) return next();
req.file.filename = `user-${req.user.id}-${Date.now()}.jpeg`;
await sharp(req.file.buffer)
.resize(500, 500)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(`public/img/users/${req.file.filename}`);
next();
};