javascript - 上传前如何调整图片大小

标签 javascript node.js amazon-s3 image-uploading image-resizing

我想在将图像上传到 s3 amazon 之前调整图像大小。 我需要 3 个不同的尺寸:调整大小(原始图像、缩略图、网页尺寸)。 我怎样才能做到这一点? 如何获取通过 POST 方法过去的图像的路径?

这是我的代码:(使用 Node js 将图像上传到 s3 amazon)

 app.post('/upload', function(request, response) {
    var ext
      , hash
      , form = new formidable.IncomingForm()
      , files = []
      , fields = [];
    form.keepExtensions = true;
    form.uploadDir = 'tmp';
    form.on('fileBegin', function(name, file) {
      ext = file.path.split('.')[1];
      hash = hasher();
      file.path = form.uploadDir + '/' + hash;
    });
    form.on('field', function(field, value) {
      fields.push([field, value]);
    }).on('file', function(field, file) {
      files.push([field, file]);
    }).on('end', function() {
      fs.readFile(__dirname + '/../tmp/' + hash, function(error, buf) {
        var req = client.put('/images/' + hash + '.png', {
          'x-amz-acl': 'private',
          'Content-Length': buf.length,
          'Content-Type': 'image/png'
        });
        req.on('response', function(res){
          var image = new S3({
            hash : hash,
            url : req.url
          });
          image.save(function(error, result) {
            if (error) {
              console.error(error);
            } else {
              response.redirect('http://' + request.headers.host + '/' + hash);
            };
          })
        });
        req.end(buf);
      });
    });
    form.parse(request);
  });

最佳答案

为此使用graphicsmagick、imagemagick。还有gm模块。 Link

示例:

gm(buf)
.resize(100, 100)
.toBuffer('PNG',function (err, buffer) {
  if (err) return handle(err);
  console.log('done!');
upload(buffer,function(err){
if(!err)
console.log("uploaded")
 }
}) //use buffer for upload

function upload(buffer,callback){
s3bucket = new AWS.S3();
params={
    Bucket: bucketName,
    Key: folder + '/' + fileName,
    Body: buffer,
    ACL: 'public-read'
}
s3bucket.putObject(params,function(err)....
}

关于javascript - 上传前如何调整图片大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37412250/

相关文章:

node.js - MongoDB find() 可以返回不同的记录吗?

amazon-web-services - 如何使用ansible将文件夹递归上传到aws s3

javascript - 将步骤数组减少为更小的数组

javascript - 我的推送菜单中的 body 动画不起作用

javascript - 打开弹出窗口并在用户单击弹出窗口外的任何位置时将其隐藏

java - AWS Java SDK 2.0 仅获取 s3 对象元

amazon-web-services - 亚马逊 S3 : Temporary Credentials

javascript - 如何在index.html中检查登录情况

node.js - Dynamodb DB 查询中的时间戳比较未按预期工作

angularjs - 构建 AngularJS 包后,如何使用 NodeJS 作为后端请求服务器来部署 AngularJS