调整大小时,锐利图像库会旋转图像吗?

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.

  • 顺序很重要。我发现 `resize(...).rotate()` 有效,而 `rotate().resize(...)` 对于某些图像不起作用。 (2认同)

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没有相同的支持)

现在它正常工作,调整大小的图像是正确的方式.

  • 您也可以使用[`rotate()`](http://sharp.pixelplumbing.com/en/stable/api-operation/#rotate):'如果没有提供角度,则根据EXIF数据确定.支持镜像,可以推断使用翻转操作. (4认同)
  • 我是唯一一个认为这种细节应该默认的人吗? (4认同)
  • 我会推荐使用rotate() 解决方案,因为 EXIF 数据可能包含有关原始照片的潜在私人信息。如果您的唯一目标是修复旋转,则不需要通过将所有这些私有数据转发到调整大小的版本来泄漏所有这些私有数据。 (3认同)