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?

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
The Lazy Log
  • 3,564
  • 2
  • 20
  • 27
  • In firefox it's upside down in both cases. I think Chrome is smart enough to rotate it automatically based in EXIF information. – dfsq Jul 09 '14 at 15:58
  • Hmm, really? In my firefox, the original is still normal and the image in img is upside down. – The Lazy Log Jul 09 '14 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 http://jsfiddle.net/7j5xJ/1/ – Kevin Lynch Jul 09 '14 at 15:59
  • 2
    http://regex.info/exif.cgi?imgurl=http%3A%2F%2Fd38daqc8ucuvuv.cloudfront.net%2Favatars%2F216%2F2014-02-19%252017.13.48.jpg It has `Orientation: Rotate 180` in EXIF. – dfsq Jul 09 '14 at 16:00
  • I have the same problem ... Did you find any good answer ? – Alex Nov 02 '14 at 08:32
  • It is my Rails application, and I was able to fix this issue by overriding the function to adjust image orientation before saving. What type of application are you developing? – The Lazy Log Nov 02 '14 at 14:19
  • 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 Jan 11 '15 at 00:52
  • If your using c# there are good comprehensive answers [Here](http://stackoverflow.com/questions/6222053/problem-reading-jpeg-metadata-orientation). – Dov Miller Nov 10 '16 at 09:53

15 Answers15

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Chet
  • 18,421
  • 15
  • 69
  • 113
  • 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 Jun 08 '15 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. – lostintranslation Jun 23 '16 at 15:59
  • 36
    This is not compatible with most of the browsers today https://caniuse.com/#search=image-orientation – Gabriel Cerutti May 12 '17 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 Oct 29 '17 at 01:02
  • 1
    @anw that is different, if you're loading the image directly not wrapped in html the mime-type is different and the browser is handling this exif metadata correctly. The chrome dev team has this issue as "wont-fix" because of the fact that fixing it would break w3 standards. This issue will likely remain unfixed until w3 updates the standards. Until then a server side solution is best. See my answer below. – deweydb Dec 02 '17 at 00:14
  • 16
    How has this got so many upvotes? It is extremely unsupported and doesn't work for anything besides firefox https://caniuse.com/#search=image-orientation – A Friend Jun 20 '18 at 23:35
  • 1
    `image-orientation` still extremely unsupported in November 2019. Don't use it. – Mason Nov 29 '19 at 03:34
  • The solution I ended up using is a micro-service that uses [`sharp`](https://www.npmjs.com/package/sharp) and calls `rotate()` which will read EXIF tags and rotate the image properly. You can also resize in here too which is nice and I just have a caching layer in front. Only hiccup is sharp doesn't work with HIEC yet. – Chet Nov 30 '19 at 20:14
  • 1
    As of 2020, not only is `image-orientation` widely supported, but it actually *defaults* to `from-image` on Chrome, Firefox, Safari and probably others. That said, some major browsers like Samsung Internet still have no support. – idmadj Sep 23 '20 at 21:37
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.

i-CONICA
  • 2,361
  • 9
  • 30
  • 45
  • 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 – The Lazy Log Jul 09 '14 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 Jul 09 '14 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 – The Lazy Log Jul 09 '14 at 16:05
  • You can use the GD library in PHP. – i-CONICA Jul 10 '14 at 07:47
  • 5
    A simpler way would be to remove orientation metadata and flip the image. Imagemagick provides convert -autoorient function which will do this. – saurabheights Mar 09 '16 at 07:27
  • I opened it in Paint then edit it, then undo it, then save it. The orientation is now okay. – Gellie Ann Jan 08 '19 at 22:16
  • @GellieAnn You're simply re-saving the image without any orientation data. In this case, your image isn't upside down, it's actually the right way up, but your orientation metadata is telling it to rotate 180º. By re-saving the image minus it's metadata your image appears the right way up. – i-CONICA Mar 16 '19 at 10:03
  • There's a dash in my imagemagick syntax that repairs the orientation: `convert -auto-orient ` – Edvard Rejthar Apr 30 '19 at 22:47
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.

Paul Chris Jones
  • 2,646
  • 1
  • 23
  • 21
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
The Lazy Log
  • 3,564
  • 2
  • 20
  • 27
11

save as png solved the problem for me.

  • 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." - https://www.labnol.org/software/tutorials/jpeg-vs-png-image-quality-or-bandwidth/5385/ – Casey Gibson Feb 15 '18 at 22:55
  • awesome, Solved Thanks – T. Shashwat Oct 19 '18 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 Sep 21 '19 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)')
});  
Bruno Portis
  • 151
  • 2
  • 11
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";
            }
        });
};
VMQ
  • 193
  • 1
  • 8
  • 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. – Methodician Feb 23 '20 at 01: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

TylerH
  • 20,799
  • 66
  • 75
  • 101
user4504661
  • 493
  • 7
  • 14
7

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

Trace DeCoy
  • 649
  • 6
  • 16
  • 1
    Ah, so this only occurs with the images taken by Samsung phone? – The Lazy Log Jul 09 '14 at 16:02
  • 4
    Happens with several. I've seen it on iPhones as well. – Trace DeCoy Jul 09 '14 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 Feb 26 '19 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)
deweydb
  • 2,238
  • 2
  • 30
  • 37
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.

Yuvraj Patil
  • 7,944
  • 5
  • 56
  • 56
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.

jeff porter
  • 6,560
  • 13
  • 65
  • 123
Kai Zou
  • 11
  • 1
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.

AlGator
  • 131
  • 2
  • 5
    But if you are developing an application where users can choose any image to upload, how to use Photoshop in that case? :) – The Lazy Log Jul 10 '17 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.

bfhaha
  • 401
  • 4
  • 6
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.

Yong
  • 584
  • 9
  • 15