from PIL import Image, ExifTags def check_image_rotation(image_path): try: image = Image.open(image_path) for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = image._getexif() if exif is not None: if orientation in exif: 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) return image except (AttributeError, KeyError, IndexError): # If the orientation tag is not found or any other error occurs, return the original image return Image.open(image_path)