Janaka
Janaka

Reputation: 2795

How to resize upload images with express server

I am using multer and multer-s3 to upload an image to s3 bucket.

I want to keep the original image as it is, but need additional thumbnail image. Then upload both of them to s3. I found that image resize can be done using sharp but not sure how to do this particular task.

Can anyone advice how to do this ?

const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');

aws.config.update({
    secretAccessKey: process.env.AWSSecretKey,
    accessKeyId: process.env.AWSAccessKeyId,
});

const s3 = new aws.S3();

const fileFilter = (req, file, cb) => {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
        cb(null, true);
    } else {
        cb(new Error("Invalid file type, only JPEG and PNG is allowed!"), false);
    }
};

const storage = multerS3({
    s3: s3,
    bucket: process.env.S3_Bucket_Name,
    acl: 'public-read',
    metadata: (req, file, cb) => {
        cb(null, {
            fieldName: file.fieldname
        });
    },
    key: (req, file, cb) => {
        cb(null, Date.now().toString())
    }

});

const upload = multer({
    fileFilter: fileFilter,
    storage: storage,
});

module.exports = upload;

Routing is done in following manner

router.post('/post/add', checkAuth, upload.single("photo"), PostController.createPost);

Upvotes: 0

Views: 116

Answers (2)

Ilijanovic
Ilijanovic

Reputation: 14924

After you saved your image you can resize it easelie.

You just need to pass the path to the image.

Note here: You can get the width and height of the image and check if the image needs an resize.

const sharp = require("sharp");

async function resizeImage(req, res) {
   let { width, height } = await sharp("path/to/image").metadata();
   let resizedImage;
   // you can check here if the image is too big. I will resize it to an width of 400
   if(width > 400) {
      await sharp("path/to/image")
          .resize({ fit: sharp.fit.contain, width: 400 })
          .jpeg({ quality: 90 })
          .toFile("path/to/thumbnail/directory);
   }
}

Upvotes: 1

Jatin Mehrotra
Jatin Mehrotra

Reputation: 11632

Try this, usage of sharpe module.Change route handler according to your needs

router.post(
  "/users/me/avatar",
  authMiddleware,
  upload.single("avatar"),
  async (req, res) => {
      const buffer = await sharpe(req.file.buffer)
        .png()
        .resize({
          width: 300,
          height: 300
        })
        .toBuffer();
      req.user.avatar = buffer;
      await req.user.save();
      res.send();
    },

Upvotes: 0

Related Questions