DEV Community

Cover image for Edit Image in NodeJS Using Sharp
Deepak Jaiswal
Deepak Jaiswal

Posted on

2 1 1 1 1

Edit Image in NodeJS Using Sharp

sometimes need to edit image properties and filter in nodejs. when their is no any image editor in frontend side then we use backend as image editor library sharp. sharp is best package in npm to edit image.

install package

npm i sharp

server.js

const express = require('express')
const app = express()
const multer  = require('multer');
const path= require('path');
const sharp = require('sharp');
const UserModel=require('./user.model');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})

const upload = multer(
{ storage: storage ,
    fileFilter: function (req, file, callback) {
        var ext = path.extname(file.originalname);
        if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
            return callback(new Error('Only images are allowed'))
        }
        callback(null, true)
    },
    limits:{
        fileSize: 1024 * 1024
    }
})

app.post('/profile', upload.single('profile'),async function (req, res, next) {
  // req.file contains the file fields

  try {
    await sharp("./uploads/"+req.file.filename)
      .resize({
        width: 150,
        height: 97
      })
      .toFile("./resize-uploads/"+req.file.filename);
    let user=await UserModel({name:req.body.name,avatar:req.file.filename}).save();

res.send(user);
  } catch (error) {
    console.log(error);
  }
})
Enter fullscreen mode Exit fullscreen mode

here first upload file in original directory image then resize image and save resize image into another directory.
also we add many functionality in sharp package to use like.

//filter image to grayscale
await sharp("./uploads/"+req.file.filename)
      .extract({ width: 400, height: 320, left: 120, top: 70 })
      .grayscale()
      .toFile("./resize-uploads/"+req.file.filename);

//rotate image 
await sharp("./uploads/"+req.file.filename)
      .rotate(40, { background: { r: 0, g: 0, b: 0, alpha: 0 } })
      .toFile("./resize-uploads/"+req.file.filename);

//blur image

    await sharp("./uploads/"+req.file.filename)
      .rotate(40, { background: { r: 0, g: 0, b: 0, alpha: 0 } })
      .blur(4)
      .toFile("./resize-uploads/"+req.file.filename);
Enter fullscreen mode Exit fullscreen mode

index.html

<form action="/profile" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="profile" accept="/image">
    <input type="text" class="form-control" placeholder="Enter Name" name="name">
    <input type="submit" value="Get me the stats!" class="btn btn-default">            
  </div>
</form>
Enter fullscreen mode Exit fullscreen mode

that is enough for this explore on sharp package to add many filter. thank you everyone.

Top comments (0)

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay