148

I have an image at this link: http://d38daqc8ucuvuv.cloudfront.net/avatars/216/2014-02-19%2017.13.48.jpg

As you can see, this is a normal image with correct orientation. However, when I set this link to src attribute of my image tag, the image becomes upside down. http://jsfiddle.net/7j5xJ/

<img src="http://d38daqc8ucuvuv.cloudfront.net/avatars/216/2014-02-19%2017.13.48.jpg" width="200"/>

Do you have any idea what is going on?

8
  • In firefox it's upside down in both cases. I think Chrome is smart enough to rotate it automatically based in EXIF information.
    – dfsq
    Commented Jul 9, 2014 at 15:58
  • Hmm, really? In my firefox, the original is still normal and the image in img is upside down. Commented Jul 9, 2014 at 15:59
  • 1
    I think the image itself is upside down and cloudfront could be rotating it in page. You could force a rotate via CSS jsfiddle.net/7j5xJ/1 Commented Jul 9, 2014 at 15:59
  • 2
    regex.info/… It has Orientation: Rotate 180 in EXIF.
    – dfsq
    Commented Jul 9, 2014 at 16:00
  • 2
    It is a problem with photo metadata that specifies orientation. I don't know why the image tag doesnt account for this. I haven't found any good answers yet...
    – Chet
    Commented Jan 11, 2015 at 0:52

15 Answers 15

96

I found part of the solution. Images now have metadata that specify the orientation of the photo. There is a new CSS spec for image-orientation.

Just add this to your CSS:

img {
    image-orientation: from-image;
}

According to the spec as of Jan 25 2016, Firefox and iOS Safari (behind a prefix) are the only browsers that support this. I'm seeing issues with Safari and Chrome still. However, mobile Safari seems to natively support orientation without the CSS tag.

I suppose we'll have to wait and see if browsers wills start supporting image-orientation.

9
  • 3
    Strangely browsers I tested (Safari, Chrome and Firefox on Mac in their recent incarnations) handle the flag properly when the image gets displayed directly without any HTML around it.
    – anw
    Commented Jun 8, 2015 at 10:27
  • 2
    Careful with this as it is experimental. Check out the Browser compatibility it doesn't look good for most browsers. Hopefully they will sort this out at some point. Commented Jun 23, 2016 at 15:59
  • 36
    This is not compatible with most of the browsers today caniuse.com/#search=image-orientation Commented May 12, 2017 at 17:42
  • 3
    Why in the world do images even have orientation metadata? If you really wanted to rotate the picture then wouldn't you just shift around the pixels and swap the width for the height?
    – Jack G
    Commented Oct 29, 2017 at 1:02
  • 16
    How has this got so many upvotes? It is extremely unsupported and doesn't work for anything besides firefox caniuse.com/#search=image-orientation
    – A Friend
    Commented Jun 20, 2018 at 23:35
28

Your image is actually upside down. But it has a meta attribute "Orientation" which tells the viewer it should be the rotated 180 degrees. Some devices/viewers don't obey this rule.

Open it in Chrome: right way up Open it in FF: right way up Open it in IE: upside down

Open it in Paint: Upside down Open it in Photoshop: Right way up. etc.

8
  • 1
    Do you have any idea how can we prevent these before user upload the image? As this image is uploaded directly by user so I need to find a way to overcome this Commented Jul 9, 2014 at 16:00
  • If it's for a service which will host images, you'd best reencode the images anyway, for dimention, filesize and security reasons, so this may fix them in the reencoded version.
    – i-CONICA
    Commented Jul 9, 2014 at 16:01
  • I see. I will need to find a better way to handle this. Maybe I need to process the image after it has been uploaded to S3 Commented Jul 9, 2014 at 16:05
  • You can use the GD library in PHP.
    – i-CONICA
    Commented Jul 10, 2014 at 7:47
  • 5
    A simpler way would be to remove orientation metadata and flip the image. Imagemagick provides convert -autoorient function which will do this. Commented Mar 9, 2016 at 7:27
20

If you have access to Linux, then open a terminal, cd to the directory containing your images and then run

mogrify -auto-orient *

This should permanently fix the orientation issues on all the images.

2
  • 4
    This worked for me, you may need to run brew install imagemagick on mac if you get command not found: mogrify
    – Kyle
    Commented Jan 12, 2020 at 16:19
  • Until the next image.. does it have any downsides?
    – Harry Bosh
    Commented May 30, 2020 at 5:03
12

I forgot to add my own answer here. I was using Ruby on Rails so it might not be applicable to your projects in PHP or other frameworks. In my case, I was using Carrierwave gem for uploading the images. My solution was to add the following code to the uploader class to fix the EXIF problem before saving the file.

process :fix_exif_rotation
def fix_exif_rotation
  manipulate! do |img|
    img.auto_orient!
    img = yield(img) if block_given?
    img
  end
end
2
  • 1
    good answer but how can I call this method on existing image file?
    – Matrix
    Commented Aug 25, 2018 at 1:13
  • You have to recreate versions. I guess something like this would work: stackoverflow.com/a/9065832/461640 Commented Dec 6, 2019 at 3:09
11

save as png solved the problem for me.

3
  • 1
    This solution is only useful for images that are not photographs: "JPG format is a lossy compressed file format. This makes it useful for storing photographs at a smaller size than a BMP. JPG is a common choice for use on the Web because it is compressed. For storing line drawings, text, and iconic graphics at a smaller file size, GIF or PNG are better choices because they are lossless." - labnol.org/software/tutorials/… Commented Feb 15, 2018 at 22:55
  • awesome, Solved Thanks Commented Oct 19, 2018 at 19:01
  • 2
    Saved it as PNG, then again back to JPG which keeps the file size low and saved the orientation correctly, thanks.
    – MDave
    Commented Sep 21, 2019 at 21:07
10

You can use Exif-JS , to check the "Orientation" property of the image. Then apply a css transform as needed.

EXIF.getData(imageElement, function() {
                var orientation = EXIF.getTag(this, "Orientation");

                if(orientation == 6)
                    $(imageElement).css('transform', 'rotate(90deg)')
});  
10

This answer builds on bsap's answer using Exif-JS , but doesn't rely on jQuery and is fairly compatible even with older browsers. The following are example html and js files:

rotate.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">
  <html>
  <head>
    <style>
      .rotate90 {
       -webkit-transform: rotate(90deg);
       -moz-transform: rotate(90deg);
       -o-transform: rotate(90deg);
       -ms-transform: rotate(90deg);
       transform: rotate(90deg);
      }
      .rotate180 {
       -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
       -o-transform: rotate(180deg);
       -ms-transform: rotate(180deg);
       transform: rotate(180deg);
      }
      .rotate270 {
       -webkit-transform: rotate(270deg);
       -moz-transform: rotate(270deg);
       -o-transform: rotate(270deg);
       -ms-transform: rotate(270deg);
       transform: rotate(270deg);
      }
    </style>
  </head>
  <body>
    <img src="pic/pic03.jpg" width="200" alt="Cat 1" id="campic" class="camview">
    <script type="text/javascript" src="exif.js"></script>
    <script type="text/javascript" src="rotate.js"></script>
  </body>
  </html>

rotate.js:

window.onload=getExif;
var newimg = document.getElementById('campic');
function getExif() {
    EXIF.getData(newimg, function() {
            var orientation = EXIF.getTag(this, "Orientation");
            if(orientation == 6) {
                newimg.className = "camview rotate90";
            } else if(orientation == 8) {
                newimg.className = "camview rotate270";
            } else if(orientation == 3) {
                newimg.className = "camview rotate180";
            }
        });
};
1
  • exif-js is now so outdated and un-maintained that it fails in some environments, such as anyplace where strict mode is enabled. We really need a solution for this. My app is frustrating the crap out of me and every work-around I have found has ample downsides. Commented Feb 23, 2020 at 1:05
8

This problem was driving me crazy too. I was using PHP on my server side so I was not able to use @The Lazy Log(ruby) & @deweydb(python) solutions. However it pointed me to the right direction. I fixed it on the backed using Imagick's getImageOrientation().

<?php 
// Note: $image is an Imagick object, not a filename! See example use below. 
function autoRotateImage($image) { 
    $orientation = $image->getImageOrientation(); 

    switch($orientation) { 
        case imagick::ORIENTATION_BOTTOMRIGHT: 
            $image->rotateimage("#000", 180); // rotate 180 degrees 
        break; 

        case imagick::ORIENTATION_RIGHTTOP: 
            $image->rotateimage("#000", 90); // rotate 90 degrees CW 
        break; 

        case imagick::ORIENTATION_LEFTBOTTOM: 
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW 
        break; 
    } 

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! 
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); 
} 
?> 

Here is the link if you want to read more. http://php.net/manual/en/imagick.getimageorientation.php

7

It's the EXIF data that your Samsung phone incorporates.

3
  • 1
    Ah, so this only occurs with the images taken by Samsung phone? Commented Jul 9, 2014 at 16:02
  • 4
    Happens with several. I've seen it on iPhones as well. Commented Jul 9, 2014 at 16:43
  • EXIF metadata may include information about the photograph itself (shutter speed, lens aperture, iso sensitivity, focus distance, etc), context data (date, time, temperature, humidity), and may contain the GPS coordinates as well as the rotation angle rounded up to 90° multiple. A vast majority of today's smartphones and cameras put these metadata in the EXIF block so IMHO it's just a matter of time that browsers apply the correct frame rotation automatically.
    – ManuelJE
    Commented Feb 26, 2019 at 13:49
6

Until CSS: image-orientation:from-image; is more universally supported we are doing a server side solution with python. Here's the gist of it. You check the exif data for orientation, then rotate the image accordingly and resave.

We prefer this solution over client side solutions as it does not require loading extra libraries client side, and this operation only has to happen one time on file upload.

if fileType == "image":
    exifToolCommand = "exiftool -j '%s'" % filePath
    exif = json.loads(subprocess.check_output(shlex.split(exifToolCommand), stderr=subprocess.PIPE))
    if 'Orientation' in exif[0]:
        findDegrees, = re.compile("([0-9]+)").search(exif[0]['Orientation']).groups()
        if findDegrees:
            rotateDegrees = int(findDegrees)
            if 'CW' in exif[0]['Orientation'] and 'CCW' not in exif[0]['Orientation']:
                rotateDegrees = rotateDegrees * -1
            # rotate image
            img = Image.open(filePath)
            img2 = img.rotate(rotateDegrees)
            img2.save(filePath)
4

It happens since original orientation of image is not as we see in image viewer. In such cases image is displayed vertical to us in image viewer but it is horizontal in actual.

To resolve this do following:

  1. Open image in image editor like paint ( in windows ) or ImageMagick ( in linux).

  2. Rotate image left/right.

  3. Save the image.

This should resolve the issue permanently.

1

I think there are some issues in browser auto fix image orientation, for example, if I visit the picture directly, it shows the right orientation, but show wrong orientation in some exits html page.

0
0

An easy way to the fix the problem, sans coding, is to use Photoshop's Save for Web export function. In the dialog box one can chose to remove all or most of an image's EXIF data. I usually just keep copyright and contact info. Also, since images coming directly from a digital camera are greatly oversized for web display it is a good idea to downsize them via Save for the Web anyway. For those that are not Photoshop savvy, I have no doubt that there are online resources for resizing an image and stripping it of any unnecessary EXIF data.

1
  • 5
    But if you are developing an application where users can choose any image to upload, how to use Photoshop in that case? :) Commented Jul 10, 2017 at 12:32
0

Here is my solution. Create a new file blank.jpg in Microsoft Paint and open (also by ms paint) the file wo.jpg which has a different orientation in Chrome. Select all and copy in wo.jpg. Then paste in blank.jpg. Save it.

0

It should be noted that browser behaviors may have changed over the years.

Currently, images' original orientation is generally respected in browsers.

See the relevant CSS property "image-orientation" for more details.

Note: This property previously used none as its initial value. It is believed that using from-image as the initial value will produce a generally better user experience, and minimal breakage, but future compat data as UAs attempt to make the change will confirm that. If that is confirmed, then it is likely that this property will be removed from CSS unless use cases other than “correct for incorrect orientation” are raised for its other values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.