Sharp image library rotates image when resizing?
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()
)
More details in the docs.
This way you don't need to retain the original metadata, keeping the overall image size smaller.
const data = await sharp(file_local)
.resize({
width: px,
})
.jpeg({
quality: quality,
progressive: true,
chromaSubsampling: "4:4:4",
})
.withMetadata()
.toFile(file_local_thumb);
Using the (.withMetadata()), to prevent rotation of image.
Aditional you can pass the width only parameter, you dont need the height.
The problem actually turned out to be this: when you resize an image, the exif data is lost. The exif data includes the correct orientation of the image, ie which way is up.
Fortunately sharp does have a feature that does retain the exif data, .withMetadata()
. So the code above needs to be changed to read:
S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
.resize(width, height)
.withMetadata() // add this line here
.toBuffer()
)
(Note that you also need to remove the .toFormat('png')
call because png does not have the same support for exif that jpeg does)
And now it works properly, and the resized image is the correct way up.