DEV Community

Cover image for Edit Image in NodeJS Using Sharp
Sandeep
Sandeep

Posted on

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.

Discussion (0)