Generating Image Thumbnails using Sharp Library in NodeJS

Prathamesh More
3 min readMar 23, 2020

--

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.

Recently I started working on a secrete project for my friend, At that time encountered some issues. We can’t send original files to the end client. We need to generate thumbnails of different sizes, reduce the file size and send it to the end client. Frontend developer will decide which size of image should displayed to user.

In this tutorial, we will be using the Sharp library.

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.

Create a directory for our project, navigate into the directory, and issue npm init to create a .json file that manages all the dependencies for our application

Install the required packages using npm command:

npm install --save express multer body-parser sharp

Create Express server

Now configure the server for accepting image files from the client.

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 });

Now configure for Sharp library to generate thumbnail.

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);
}
});

Now create a route for accepting our files.

//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);
}
});

Note: First create ‘upload’ directory in your root project directory.

sharp function takes file path to be processed.

resize function takes the width and height sizes of the image.

toFile function takes a storage path to store the processed files.

You can do lots of things using Sharp. Refer documentation.

You can upload also upload multiple files at the time too.

Just use upload.array('images', 100) .

Upload image

The data type should be file . If you using HTML form then don't forget the enctype="multipart/form-data" in your form.

Original image and thumbnail stored in the same upload directory of the server.

The output of image processing

Code

Learn more about file uploading on server

Learn more about developing RESTful APIs

Thank you!

Happy coding :)

https://pprathameshmore.github.io/

--

--

Prathamesh More
Prathamesh More

Written by Prathamesh More

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