Scott Daniel
Scott Daniel

Reputation: 1103

Browser Image Upload is Rotated if Exif Orientation Exists

I am uploading images using the following simple component:

export function FileUploader({ file, setFile }) {

  // Handler for file selection
  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];

    if (selectedFile) {
      setFile(selectedFile);
    }
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />

      {file && (
        <div>
          <p><strong>Selected File:</strong> {file.name}</p>
          <p><strong>File Type:</strong> {file.type}</p>
          <p><strong>File Size:</strong> {(file.size / 1024).toFixed(2)} KB</p>
        </div>
      )}
    </div>
  );
}

If the image uploaded contains an exif Orientation that is something other than 1 (not rotated), the image data that is saved is rotated, but the exif Orientation setting is preserved. This results in the image being rotated again by the browser when it is displayed.

For example, if the orientation is 3 (flip horizontal), the image saved by the backend will be flipped, but the exif will still indicate it should be flipped again.

If I manually remove the exif orientation from the image after it is uploaded, the image will be displayed correctly.

Upvotes: -1

Views: 30

Answers (2)

Scott Daniel
Scott Daniel

Reputation: 1103

I erroneously thought that the browser was rotating the image before it was uploaded, but it turns out it was jimp that was rotating the image in the backend.

This is a known issue with older versions of jimp. Upgrading from version 0.22 to 1.6.0 seems to have solved the problem.

https://github.com/jimp-dev/jimp/issues/733

https://github.com/jimp-dev/jimp/issues/920

Version 1.6.0 still rotates the image based on the exif data, but it removes the orientation flag from the image data as well. This allows it to be displayed correctly in the browser.

Upvotes: -1

himture
himture

Reputation: 29

To fix the issue of browser rotating the image again you can use CSS to prevent the browser from reading the EXIF orientation data.

You can use:

style={{ imageOrientation: 'none' }}

add this to the image tag when displaying the image as

<img src={URL.createObjectURL(file)} style={{ imageOrientation: 'none' }} alt="Image from backend" />

This should fix your issue of browser rotating the image again.

Upvotes: 0

Related Questions