프로그래밍

windows, ubuntu os rotated image python

개발독학 2021. 7. 16. 18:34

width, height inverted image를 다루는 방법

windows와 ubuntu에서 본 이미지의 width, height가 달라보이는 문제가 있었다.
모바일 기기(ex. 갤럭시, 아이폰)에서 찍은 이미지의 경우 회전 metadata가 설정되고, 돌아간 채로 저장되는 이미지들이 있어서 이 경우는 아래 코드처럼 체크해서 실제 눈으로 보이는 크기에 맞도록 수정해줘야 한다.

from PIL import Image, ExifTags

try:
    image=Image.open(filepath)

    for orientation in ExifTags.TAGS.keys():
        if ExifTags.TAGS[orientation]=='Orientation':
            break

    exif = image._getexif()

    if exif[orientation] == 3:
        image=image.rotate(180, expand=True)
    elif exif[orientation] == 6:
        image=image.rotate(270, expand=True)
    elif exif[orientation] == 8:
        image=image.rotate(90, expand=True)

    image.save(filepath)
    image.close()
except (AttributeError, KeyError, IndexError):
    # cases: image don't have getexif
    pass