有没有办法在使用 multer 功能的 Node.js 中减小图像大小并调整图像大小?

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

我需要调整图片大小并将其压缩到最小,然后上传到目录中。有什么帮助吗?


1
尝试使用npm中的“multer-imager”模块,在将图像上传到目录之前减小图像大小。 - sugandhi
2个回答

5
你可以为 multer 创建一个定制的存储引擎。
根据官方文档,自定义存储引擎是公开两个函数的类:_handleFile_removeFile
这是创建自定义存储引擎的官方模板(链接):
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 processorGraphicsMagick for node

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接