使用 Node.js 和 Sharp 调整来自 AWS S3 的图像大小

Resizing images from AWS S3 with Node.js and Sharp

我正在尝试在我的 API 上创建一个端点,我可以在其中按需调整来自 S3 的图像的大小。我已经让它工作了,但是 return 调整大小后的图像大约需要 7 秒,而 return 不调整大小的图像大约需要 800 毫秒。我是处理图像的新手,因此决定使用 sharp 包,因为它看起来非常简单易用。我想知道是否有人可以告诉我我做错了什么?或者加快速度的方法?还是 sharp 只是慢?

我的代码是:

const getCommand = new GetObjectCommand({
    Bucket: 'mybucket',
    Key: 'myfile'
});
const getResponse = await s3Client.send(getCommand);

// Set response headers
response.set('Content-Length', getResponse.ContentLength);
response.set('Content-Type', getResponse.ContentType);
response.statusCode = 200;

// Stream response
getResponse.Body.pipe(response);
// GetResponse.Body.pipe(sharp().resize(40, 40)).pipe(response)

提前致谢!

尝试删除 Content-Length header:

response.set('Content-Length', getResponse.ContentLength);

当我测试你的代码时,这提高了性能。

检查您是否观察到相同的改进。