3

I cannot resize image. I am using multer for getting files, but how can I resize this image? I tried imagestick but fs didn't save them.

  router.post('/uploadAvatar', 
    multer({
      dest: './public/uploads/images/avatars',
      rename: function (fieldname, filename) {
        return 'avatar'+Date.now();
      }
    }), function(req, res) {
      // resize image
      res.json(newPath);
  });
pvorb
  • 7,157
  • 7
  • 47
  • 74
user256968
  • 371
  • 1
  • 5
  • 18

1 Answers1

11

I like Sharp module to play with images in Node.js:

   router.post('/uploadAvatar', 
    multer({
      dest: './public/uploads/images/avatars',
      rename: function (fieldname, filename) {
        return 'avatar'+Date.now();
      }
    }), function(req, res) {
      // resize image
      sharp(newPath).resize(300, 200).toFile(newPath, function(err) {
         if (err) {
           throw err;
         }
         // output.jpg is a 300 pixels wide and 200 pixels high image
         // containing a scaled and cropped version of input.jpg
         res.json(newPath);
      });
  });
michelem
  • 14,430
  • 5
  • 50
  • 66
  • I can resize the image perfectly. But, I just want to keep the resized file only. Every time after the resizing i have to delete the old one and keep the resized file. If i put the`newpath` as same (same origin and destination), then it will shows the error. In short, I want to know whether there is a solution such that the uploaded image can be resized by overwriting the original file uploaded.? – Mathew John May 10 '18 at 08:16
  • I experienced the same issue with php. what i did was to give the original image just a name eg orginal.jpg and then strip the binding dot extension(.jpg) rewrite it another file extension that is not executable eg. original.me. what this does is that any image uploaded by any user and resizing. the original image will be name original.me thus they will be replacing each other. at the end you will just have only original.me and unlimited amount of resized file based on number of image uploads – chinazaike Aug 16 '18 at 21:28