Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharp image library rotates image when resizing?

When using the sharp image resize library https://github.com/lovell/sharp for node.js, the image is being rotated.

I have no code thats says .rotate(), so why is it being rotated and how can I stop it from rotating?

I'm using the serverless-image-resizing example provided by AWS: https://github.com/awslabs/serverless-image-resizing that uses lambda to resize images on the fly if the thumbnail does not exist

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)) 

Original large image:

enter image description here

Resized image: note it has been rotated as well:

enter image description here

like image 629
JK. Avatar asked Feb 10 '18 01:02

JK.


People also ask

How do I resize an image in sharp?

The resizeImage() function chains the sharp module's resize() method to the sharp instance. The method takes an object as an argument. In the object, you set the image dimensions you want using the width and height property. Setting the width to 150 and the height to 97 will make the image 150px wide, and 97px tall.

What is EXIF orientation?

The EXIF orientation value is used by Photoshop and other photo editing software to automatically rotate photos, saving you a manual task.

Does Sharp compress images?

sharp compresses images faster than most other Node. js modules, like ImageMagick, Jimp, or Squoosh, and produces high-quality results. sharp converts large common image formats to smaller, web-friendly images. sharp can read JPEG, PNG, WebP, AVIF, TIFF, GIF, and SVG image formats.


1 Answers

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.

like image 66
JK. Avatar answered Sep 21 '22 11:09

JK.