The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Fixing the issue of rotated images after resizing with sharp

posted on 20.2.2023 by Below Surface in "Node.js"

Sharp is a lovely resizing package for Node.js applications. For example, this code can reduce the images file size big time:

await sharp(req.file.path).resize({ width: 1000 })
                          .jpeg({ quality: 50 })
                          .toFile(filePath);

But there is an error with some images. They will be rotated after resizing. This is because the meta data is lost during resizing and in my case, this is what I actually want. But of course, I want my images in the correct rotation and here is the fix: Just add .rotate() before calling the .resize() method, so your code looks like this:

await sharp(req.file.path).rotate()
                          .resize({ width: 1000 })
                          .jpeg({ quality: 50 })
                          .toFile(filePath);

Tags:

node.js
sharp
npm package
image resizing
rotation fix

Sources:

https://www.npmjs.com/package/sharphttps://stackoverflow.com/questions/48716266/sharp-image-library-rotates-image-when-resizing

More posts of this category

Read url parameters in Node.js/Express

Params can be used to include variables within the url. Learn how to read them in the backend

Node.js