6

我已经使用下面的代码在 nodejs 中使用简单的图像 npm 模块调整了图像的大小。

var easyimg = require('easyimage');

easyimg.rescrop({
     src:'1.jpg', dst:'/var/www/html/bangalore.jpg',
     width:100, height:100

  }),function(image,err){
     // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
     if(image){
     console.log(image);   
     }
     else{
     console.log(err);    
     }

  }

我已经成功输出。然后我使用下面的代码和 multer 将我的图像上传到 s3。

var storage = multerS3({
              s3: s3,
              bucket: 'my_bucket_name',
              key: function (req, file, cb) {
                  console.log(file);
                  file_name = file.originalname;
                  var newFileName = Date.now() + "-" + file.originalname;
                  cb(null, newFileName);
              }
           });
              var upload = multer({storage: storage}).single('profileImage');
             upload(req, resq, function (err,res,response) {
              console.log(response);
             });

现在我的问题是如何在上传到 s3 之前调整图像大小,然后将调整后的图像上传到 s3?

我也尝试过使用 multer-imager 模块。

var transfer = imager({

              secretAccessKey: 'secretAccessKey',
              accessKeyId: 'myaccesskey',
              dirname:'avatar',
              bucket: 'my_bucket',

              region:'myregion',

              key: function (req, file, cb) {
                  console.log(file);
                  file_name = file.originalname;
                  var newFileName = Date.now() + "-" + file.originalname;

                cb(null, newFileName);
                console.log(newFileName);

              },                                    //
    gm: {                                 // [Optional]: define graphicsmagick options
      width: 200,                         // doc: http://aheckmann.github.io/gm/docs.html#resize
      height: 200,
      options: '!',
      format: 'png'                       // Default: jpg
    }
           });
              var upload = multer({storage: transfer}).single('myimage');
             upload(req, resq, function (err,res,response) {
              console.log(req.file); //i am getting this as undefined
             })

但它不起作用。在“req.file”中,我变得未定义。?

4

1 回答 1

11

为什么不使用multer-s3-transofrm和 multer s3 模块的内置转换?

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'some-bucket',
    shouldTransform: function (req, file, cb) {
      cb(null, /^image/i.test(file.mimetype))
    },
    transforms: [{
      id: 'original',
      key: function (req, file, cb) {
        cb(null, 'image-original.jpg')
      },
      transform: function (req, file, cb) {
        //Perform desired transformations
        cb(null, sharp().resize(600, 600).max())
      }
    }]
  })
})

从文档:

可选shouldTransform选项告诉 multer 是否应该在文件上传之前对其进行转换。默认情况下,它设置为 false。如果设置为 true,则必须添加 transforms 选项,它告诉如何转换文件。

transforms选项应该是一个数组,包含可以具有属性 id、key 和 transform 的对象。

此示例使用Sharp进行变换(众所周知的Node.js 图像处理模块)。

于 2017-12-08T17:51:56.217 回答