Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save petergi/a1b12edb225f7a722acc6ac273e5059b to your computer and use it in GitHub Desktop.

Select an option

Save petergi/a1b12edb225f7a722acc6ac273e5059b to your computer and use it in GitHub Desktop.
This Python script walks a directory, finds images, and rotates any portrait-oriented image 90° counter-clockwise so it becomes landscape. # Landscape images are left alone. It also respects EXIF orientation, which saves you from the classic “why is this one upside down?” ritual.
from PIL import Image, ImageOps
import os
IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png", ".tiff", ".bmp")
def rotate_portrait_images(directory):
for filename in os.listdir(directory):
if not filename.lower().endswith(IMAGE_EXTENSIONS):
continue
path = os.path.join(directory, filename)
try:
with Image.open(path) as img:
# Normalize orientation using EXIF data
img = ImageOps.exif_transpose(img)
width, height = img.size
# Portrait → rotate CCW
if height > width:
img = img.rotate(90, expand=True)
img.save(path)
print(f"Rotated: {filename}")
else:
print(f"Skipped (already landscape): {filename}")
except Exception as e:
print(f"Error processing {filename}: {e}")
if __name__ == "__main__":
rotate_portrait_images("/path/to/your/image/directory")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment