【发布时间】: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