【问题标题】:Resize and compress image from URL and upload to S3从 URL 调整大小和压缩图像并上传到 S3
【发布时间】:2021-12-09 21:54:26
【问题描述】:

我有一个函数应该从外部 URL 获取图像,用清晰优化它,然后将图像上传到 S3。

但我似乎无法敏锐地调整大小和压缩。

这是我当前的代码:

const got = require('got');
const sharp = require('sharp');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
  credentials,
});

async function uploadFile(url) {
  // Get file
  const response = await got(url, { responseType: 'buffer' });

  // Resize, compress and convert image before upload
  const { data, info } = await sharp(response.body)
    .resize({ width: 512 })
    .jpeg({ quality: 70 })
    .toBuffer();

  console.log('data:', data);

  const uploadedFile = await s3
    .upload({
      Bucket: bucket,
      Key: 'filename.jpg',
      Body: data,
      ContentType: 'image/jpeg',
    })
    .promise();

  console.log('uploadedFile:', uploadedFile);
}

我得到的错误:Input file is missing

调用sharp方法时代码失败。

我从 response.body link 得到的那种输出

【问题讨论】:

  • 你试过await sharp(Buffer.from(response.body))吗?
  • 我在 png 和 jpg 图像上尝试它时收到Input buffer contains unsupported image format
  • got库不是很熟悉,但是好像需要异步解析body,例如:const body = await got(url).buffer(),它本质上设置了responseType: buffer和resolveBodyOnly: true。
  • 当我这样做时得到got(...).buffer is not a function,不知道为什么。它应该可以工作,基于我发现的这个例子:stackoverflow.com/a/63965189/10014988

标签: javascript node.js amazon-web-services amazon-s3 sharp


【解决方案1】:

我觉得你需要做两处改动,如下:

const body = await got(url).buffer();

和:

const data = await sharp(body)
    .resize({ width: 512 })
    .jpeg({ quality: 70 })
    .toBuffer();

通过这些更改,您的代码对我有用。我从网上下载了一张随机图片并成功上传到 S3。另外,请确保您有最新的 got 和 sharp 软件包。

【讨论】:

  • 看起来我不得不强制安装一个从未有过的主要版本 got,即使我是最近才安装的。
猜你喜欢
  • 2018-02-25
  • 2023-04-11
  • 1970-01-01
  • 2020-06-16
  • 2015-05-19
  • 1970-01-01
  • 2011-09-18
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多