JK.*_*JK. 8 amazon-s3 image-resizing node.js aws-lambda sharp
对于node.js 使用清晰图像调整大小库https://github.com/lovell/sharp时,图像正在旋转.
我没有代码说.rotate(),为什么它被旋转,我怎么能阻止它旋转?
我使用的是由AWS提供的无服务器,图像缩放例如: https://github.com/awslabs/serverless-image-resizing使用拉姆达在飞行中调整图像如果缩略图不存在
S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
.resize(width, height)
.toFormat('png')
.toBuffer()
)
.then(buffer => S3.putObject({
Body: buffer,
Bucket: BUCKET,
ContentType: 'image/png',
Key: key,
}).promise()
)
.then(() => callback(null, {
statusCode: '301',
headers: {'location': `${URL}/${key}`},
body: '',
})
)
.catch(err => callback(err))
Run Code Online (Sandbox Code Playgroud)
原始大图:
已调整大小的图片:请注意它已被旋转:
mih*_*hai 33
The alternative solution is to actually call .rotate() before resize. This will auto-orient the image based on the EXIF data.
.then(data => Sharp(data.Body)
.rotate()
.resize(width, height)
.toBuffer()
)
Run Code Online (Sandbox Code Playgroud)
More details in the docs.
This way you don't need to retain the original metadata, keeping the overall image size smaller.
JK.*_*JK. 11
问题实际上是这样的:当您调整图像大小时,exif数据会丢失.exif数据包括图像的正确方向,即哪个方向上升.
幸运的是,sharp确实具有保留exif数据的功能.withMetadata().所以上面的代码需要更改为:
S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
.resize(width, height)
.withMetadata() // add this line here
.toBuffer()
)
Run Code Online (Sandbox Code Playgroud)
(请注意,您还需要删除该.toFormat('png')调用,因为png对jpeg执行的exif没有相同的支持)
现在它正常工作,调整大小的图像是正确的方式.