Node.JS Resize Image Before Upload Using Multer Sharp

Hey Everyone,

In this article, we will learn how to resize the image before uploading using multer, sharp with node js, and express js. we will help you to give an example of node.js image uploading with multer. This article will focus on the sharp module. sharp is a popular Node.js image processing library that supports various image file formats, such as JPEGPNGGIFWebPAVIFSVG, and TIFF.

I will give you step by step simple example of how to resize the image before uploading using multer, sharp with node js, and express js. In this example we will simply upload an image and resize it with 200*200 and the quality will be 90%. let’s follow the below steps:

Step 1: Create Node App

Execute the following command on the terminal or command prompt to create the node js app:

mkdir my-app
cd my-app
npm init

Step 2: Install express and multer

Execute the following command to install express and multer dependencies in your node js app:

npm install express multer --save
npm install sharp --save

Step 3 – Create Index.js File

Create an index.js file, So go to your app root directory and create it. Now import the below dependencies in index.js file :

const express = require('express');
const multer = require('multer');
const fs = require('fs');
const sharp = require('sharp');

Now Configure multer package to store files in the directory :

const storage = multer.memoryStorage(); 
var upload = multer({ storage: storage });

Create image file upload routes :

app.post('/upload', upload.single('image'),async (req, res) => {
    fs.access('./data/uploads',(err)=>{
        if(err){
            fs.mkdirSync('./data/uploads');
        }
    });
       await sharp(req.file.buffer)
        .resize(400,200)
        .toFile('./data/uploads/' + req.file.originalname)
        res.send(req.file);
});

Here is, Complete code of the index.js file :

const express = require('express');
const multer = require('multer');
const sharp = require('sharp');
const fs = require('fs');
const app = express();
const port = 3000;

const storage = multer.memoryStorage();
var upload = multer({ storage: storage });
app.post('/upload', upload.single('image'),async (req, res) => {
    fs.access('./data/uploads',(err)=>{
        if(err){
            fs.mkdirSync('./data/uploads');
        }
    });
       await sharp(req.file.buffer)
        .resize(400,200)
        .toFile('./data/uploads/' + req.file.originalname)
        res.send(req.file);
});
app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

Step 4 – Start App Development Server

You can use the following command to run your application :

npm start

Output:

Also Check, Send mail using OAuth in Node.js.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories