是否有任何选项可以减小图像大小并在具有多种功能的nodejs中调整图像大小?

Is there any option to reduce the image size and resize the image in nodejs with multer functionality?

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

我需要调整图像大小并将图像压缩到最小尺寸并上传到 directory.Any 帮助?

这可以使用 multer-imager npm 模块来完成。

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

确保在此之前安装 graphicsmagick(不是 npm 模块)。 点击下面的link安装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/

然后安装 multer-imager 和 gm npm 模块。

您可以为 multer 创建自定义存储引擎。

根据 official documentation,自定义 存储引擎 是 类,公开两个函数:_handleFile_removeFile

这是用于创建自定义存储引擎 (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)
}

您可以在将图像保存到磁盘之前使用 _handleFile 功能缩小图像大小。

为了减小图像大小,您可以选择各种 npm 模块来完成这项工作。一些值得检查的模块是 Sharp, Light-weight image processor and GraphicsMagick for node.