如何在Node.js中使用Multer调整图像大小

10

Multer已经有了限制文件大小的属性,但这个属性仅限制图片大小,不能调整图片大小。我的问题是,如果图片超过“限制大小”,应该如何调整图片大小?

Multer已经拥有限制文件大小的属性,但是这个属性只能限制图片的大小,而不能对图片进行调整。我的问题是,如果图片大小超过了“限制大小”,那么该如何调整图片大小呢?

var storageOptions = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'useravatars/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

var avatarUpload = multer({
    storage: storageOptions,
    limits: {
        fileSize: 1000000
    }
}).single("avatar");
2个回答

9

这取决于您是否想要存储调整大小后的图像。

无论如何,您都需要使用库来处理缩放操作。 Sharp 是一个非常好的选择。

在路由处理程序中调整大小(文件存储到磁盘后):

sharp(req.file).resize(200, 200).toBuffer(function(err, buf) {
  if (err) return next(err)

  // Do whatever you want with `buf`
})

另一个选择是创建自己的存储引擎,这种情况下,您将收到文件数据,调整大小,然后存储到磁盘中。 (摘自 https://github.com/expressjs/multer/blob/master/StorageEngine.md):

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)
    var resizer = sharp().resize(200, 200).png()

    file.stream.pipe(resizer).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)
}


由于命令提示符抛出以下错误,因此无法安装“sharp模块”:sharp@0.18.4 install: node-gyp rebuild Exit status 1在sharp@0.18.4安装脚本中执行“node-gyp rebuild”失败。 - Manimaran
如果输出的最后一行是“OK”,那么就没问题了。 - André Werlang

0
const path = require("path");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "/uploads"));
  },
  filename: function (req, file, cb) {
    cb(null, uuid.v4() + `${path.extname(file.originalname)}`);
  }
});

const limits = {
  fields: 10,
  fileSize: 500 * 1024,
  files: 1,
};

const upload = multer({ storage, limits });
const baseUrl = "http://localhost:3000/files/";
router.post("/upload", upload.single("file"), async (ctx, next) => {
  ctx.body = {
    code: 1,
    data: baseUrl + ctx.file.filename,
  };
});

来自评论:嗨,仅包含代码或命令的答案在 Stack Overflow 上是不被鼓励的,因为它们没有解释它如何解决问题。请编辑您的答案,解释这段代码的作用以及它如何回答问题,以便对有类似问题的人有所帮助。请参阅:如何撰写好的答案? - sɐunıɔןɐqɐp

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