Is it possible to reduce image size and resize image in nodejs using multer function?

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })

      

I need to resize the image and compress the image size to the lowest level and upload it to a directory. Any help?

+3


source to share


2 answers


This can be done using mpm image mode in npm mode.

http://www.npmjs.com/package/multer-imager

make sure you install graphicsmagick (not npm module) before doing this. Follow below link to install graphicsmagick.



http://linuxg.net/how-to-install-graphicsmagick-1-3-18-on-ubuntu-13-10-13-04-12-10-12-04-linux-mint-16-15- 14-13-pear-os-8-7-and-elementary-os-0-2 /

Then install multer-imager module and gm npm.

0


source


You can create a custom storage engine for multer.

According to the official documentation, custom Storage Engines are classes that expose two functions: _handleFile

and _removeFile

.

Here is the official template for creating a custom storage engine ( Link ):



var fs = require('fs')

function getDestination (req, file, cb) {
  cb(null, '/dev/null')
}

function MyCustomStorage (opts) {
  this.getDestination = (opts.destination || getDestination)
}

MyCustomStorage.prototype._handleFile = function _handleFile (req, file, cb) {
  this.getDestination(req, file, function (err, path) {
    if (err) return cb(err)

    var outStream = fs.createWriteStream(path)

    file.stream.pipe(outStream)
    outStream.on('error', cb)
    outStream.on('finish', function () {
      cb(null, {
        path: path,
        size: outStream.bytesWritten
      })
    })
  })
}

MyCustomStorage.prototype._removeFile = function _removeFile (req, file, cb) {
  fs.unlink(file.path, cb)
}

module.exports = function (opts) {
  return new MyCustomStorage(opts)
}

      

You can reduce the size of the image in a function _handleFile

before saving it to disk.

To reduce image size, you can choose from several npm modules that do the job. Some tested modules are Sharp , Light Image Processor and GraphicsMagick for node .

0


source







All Articles