6

I am using Jimp (https://www.npmjs.com/package/jimp) library to crop the image.

Crop is working fine but I only have an issue with image orientation.

Sometimes, user uploaded rotated images and its result rotated cropped images.

I went through with https://www.npmjs.com/package/jimp documentation but couldn't find anything related to this.

Here are couple of links I went through but didn't helped:

https://justmarkup.com/articles/2019-10-21-image-orientation/

Accessing JPEG EXIF rotation data in JavaScript on the client side

Please help

Parveen Kumar
  • 397
  • 1
  • 5
  • 12

2 Answers2

0

So, long story short: jimp correctly reads images rotated via exif orientation property and rearranges the pixels as if the exif/orientation property didn't exist, but then also stores the old exif property instead of resetting it to 1 as it should for it to be displayed properly on every device.

The simplest solution I was able to implement was using exif-auto-rotate to rotate the image pixels and reset the exif property on the frontend before uploading the (base64 encoded) image to the backend:

    import Rotator from 'exif-auto-rotate';
    
    // ...
    
    const [file] = e.target.files;
    
    const image = await Rotator.createRotatedImageAsync(file, "base64")
        .catch(err => {
            if (err === "Image is NOT have a exif code" || err === "Image is NOT JPEG") {
                // just return base64 encoded image if image is not jpeg or contains no exif orientation property
                return toBase64(file)
            }
            // reject if other error
            return Promise.reject(err)
        });

If you need to do this on the backend then you are probably better off using jpeg-autorotate with buffers as suggested here:

const fileIn = fs.readFileSync('input.jpg')
const jo = require('jpeg-autorotate')
const {buffer} = await jo.rotate(fileIn, {quality: 30})
const image = await Jimp.read(buffer)

More info on browser-based exif orientation issues:

EXIF Orientation Handling Is a Ghetto

r.delic
  • 795
  • 7
  • 18
0

just change the jimp version to

"jimp": "0.8.5",
Gonen
  • 4,005
  • 1
  • 31
  • 39
user20437544
  • 51
  • 1
  • 1
  • 1
    It would be nice to give a brief explanation of how this works / how it solves the problem, and how it's different than existing answers. – starball Dec 22 '22 at 03:31