Search code examples
pythonimagepython-imaging-librarydimensions

height or width first in Python?


Here is the problem I've run into:

I have an image that has 3024 x 4032 in Dimensions, and usually just by looking at it, you know it's a vertical image, but it's not for whatever reasons. enter image description here

from PIL import Image

img = Image.open("xxx.jpg")
print(img.size)

It turns out to be (4032 x 3024) in dimensions, why is that?

In most of the cases, it prints out as expected, where dimensions has width as its first argument(img.size[o]), and height as its second argument(img.size[1]).

It looks like width and height aren't always in the right position? Or did I miss something?


Solution

  • Your picture might be rotated in exif tags.

    Some mobile phones and cameras are "rotating" image when making a photo by this special field, not actually rotating pixel matrix of the image. So, in clever viewer programm you'll see dimensions of picture as it should be with applied exif rotation, but PIL will load it "as is" without any rotation tag involved.

    So, you can check, if image was rotated, and then swap width and height:

    from PIL import Image, ExifTags
    
    img = Image.open("xxx.jpg")
    
    def get_image_size(img):
        """
        The function return REAL size of image
        """
    
        # Lets get exif information in a form of nice dict:
        # It will be something like: {'ResolutionUnit': 2, 'Orientation': 6, 'YCbCrPositioning': 1}
        exif = {
            ExifTags.TAGS[k]: v
            for k, v in img._getexif().items()
            if k in ExifTags.TAGS
        }
    
        size = img.size
    
        # If orientation is horizontal, lets swap width and height:
        if exif.get("Orientation", 0) > 4:
            size = (size[1], size[0])
    
        return size
    
    print(get_image_size(img))
    

    Exif orientation is a number 1-8, that means the REAL image orientation

    Info about it could be found here: http://sylvana.net/jpegcrop/exif_orientation.html