当使用 Node.js 的锐利图像调整大小库 https://github.com/lovell/sharp 时,图像正在旋转。
我没有表示 .rotate() 的代码,那么为什么它会被旋转以及如何阻止它旋转?
我正在使用 AWS 提供的 serverless-image-resizing 示例:https://github.com/awslabs/serverless-image-resizing,如果缩略图不存在,它会使用 lambda 动态调整图像大小
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))
原图大图:
调整图像大小:请注意它也已旋转:
问题实际上是这样的:当你调整图像大小时,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()
)
(请注意,您还需要删除
.toFormat('png')
调用,因为 png 对 exif 的支持与 jpeg 不同)
现在它可以正常工作了,并且调整大小的图像是正确的。
替代解决方案是在
.rotate()
之前实际调用 resize
。这将根据 EXIF 数据自动调整图像方向。
.then(data => Sharp(data.Body)
.rotate()
.resize(width, height)
.toBuffer()
)
更多详细信息请参阅文档。
这样您就不需要保留原始元数据,从而使整体图像尺寸更小。
const data = await sharp(file_local)
.resize({
width: px,
})
.jpeg({
quality: quality,
progressive: true,
chromaSubsampling: "4:4:4",
})
.withMetadata()
.toFile(file_local_thumb);
使用(.withMetadata()),防止图像旋转。
另外,您可以仅传递宽度参数,不需要高度。
更新了无服务器图像处理程序 5.0 的答案,自 2020 年 10 月起使用 CloudFormation Stack 模板进行部署:
我将
.rotate()
附加到 image-handler.js
的第 50 行,它的效果就像一个魅力:
const image = sharp(originalImage, { failOnError: false }).rotate();
我以特定于 AWS Serverless Image Handler 的相关方式修复了此问题,无需更改代码。我正在编辑列表中传递
"rotate":null
。
在阅读最新的(5.2.0)代码时,看起来他们试图解决这个问题,但在我添加
"rotate":null
之前它仍然对我不起作用
这是 Github 上的相关问题:https://github.com/awslabs/serverless-image-handler/issues/236
如果您使用带有 IPX 提供程序的 Nuxt Image 组件到达这里,这就是我解决它的方法:在
nuxt.config.js
文件中,添加以下内容:
buildModules: [
[
'@nuxt/image',
{
sharp: {
withMetadata: true,
},
},
],
],
请注意,模块中的选项比记录的选项更多:https://github.com/nuxt/image/blob/61bcb90f0403df804506ccbecebfe13605ae56b4/src/module.ts#L20