Generating Image Thumbnails using Sharp Library in NodeJS

As a Backend developer, we deal with performing a lot’s background tasks on the server and serve proper responses to end clients. In this tutorial, we will learn to generate thumbnails using Sharp from uploaded images using Multer.

Packages and software requirements

  1. Node.js — Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
  2. Express — Fast, unopinionated, minimalist web framework for Node.js
  3. Sharp — High-performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images. Uses the libvips library
  4. Multer — Multer is a Node.js middleware for handling, which is primarily used for uploading files.
  5. Postman — A collaboration platform for API development.

Project setup

We will be using the Node Express framework for this project. Of course, you’ll need to have Node installed.

npm install --save express multer body-parser sharp
const multer  = require('multer');const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads');
},
filename: (req, file, cb) => {
console.log(file);
cb(null, Date.now() + path.extname(file.originalname));
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype == 'image/jpeg' || file.mimetype == 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
}
const upload = multer({ storage: storage, fileFilter: fileFilter });
const sharp = require('sharp');sharp(req.file.path).resize(200, 200).toFile('uploads/' + 'thumbnails-' + req.file.originalname, (err, resizeImage) => {
if (err) {
console.log(err);
} else {
console.log(resizeImage);
}
});
//Upload route and sharp configure
app.post('/upload', upload.single('image'), (req, res, next) => {
try {
sharp(req.file.path).resize(200, 200).toFile('uploads/' + 'thumbnails-' + req.file.originalname, (err, resizeImage) => {
if (err) {
console.log(err);
} else {
console.log(resizeImage);
}
})
return res.status(201).json({
message: 'File uploded successfully'
});
} catch (error) {
console.error(error);
}
});
Upload image
The output of image processing

Learn more about file uploading on server

Passionate, Self-taught Full Stack MERN Web Developer that loves designing and building modern websites, applications, and APIs.