# The EXIF tag that holds orientation data.
EXIF_ORIENTATION_TAG = 274
# Obviously the only ones to process are 3, 6 and 8.
# All are documented here for thoroughness.
ORIENTATIONS = {
1: ("Normal", 0),
2: ("Mirrored left-to-right", 0),
3: ("Rotated 180 degrees", 3),
4: ("Mirrored top-to-bottom", 0),
5: ("Mirrored along top-left diagonal", 0),
6: ("Rotated 90 degrees", 4),
7: ("Mirrored along top-right diagonal", 0),
8: ("Rotated 270 degrees", 2)
}
def fix_orientation(img:Image):
try:
orientation = img._getexif()[EXIF_ORIENTATION_TAG]
except (TypeError, AttributeError, KeyError):
print('error')
return img
if orientation in [3, 6, 8]:
degrees = ORIENTATIONS[orientation][1]
img = img.transpose(degrees)
return img
else:
return img
一般图片只会出现 3,6,8这三种情况;
本文参考:https://blog.csdn.net/ghost_blade/article/details/102919937;但是使用参考中的库会出现黑边问题,原因是该库使用了 img.rotate 方法,这里将其替换成 img.transpose,并做了参数处理,完美解决图片旋转问题。