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


This content originally appeared on DEV Community and was authored by Sandeep

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

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

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>

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


This content originally appeared on DEV Community and was authored by Sandeep


Print Share Comment Cite Upload Translate Updates
APA

Sandeep | Sciencx (2022-06-25T18:07:21+00:00) Edit Image in NodeJS Using Sharp. Retrieved from https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/

MLA
" » Edit Image in NodeJS Using Sharp." Sandeep | Sciencx - Saturday June 25, 2022, https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/
HARVARD
Sandeep | Sciencx Saturday June 25, 2022 » Edit Image in NodeJS Using Sharp., viewed ,<https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/>
VANCOUVER
Sandeep | Sciencx - » Edit Image in NodeJS Using Sharp. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/
CHICAGO
" » Edit Image in NodeJS Using Sharp." Sandeep | Sciencx - Accessed . https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/
IEEE
" » Edit Image in NodeJS Using Sharp." Sandeep | Sciencx [Online]. Available: https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/. [Accessed: ]
rf:citation
» Edit Image in NodeJS Using Sharp | Sandeep | Sciencx | https://www.scien.cx/2022/06/25/edit-image-in-nodejs-using-sharp/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.