Skip to content

Instantly share code, notes, and snippets.

@pluscubed
Last active November 5, 2019 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pluscubed/7f883c23c9dadd99c27ea82d20a80d5a to your computer and use it in GitHub Desktop.
Save pluscubed/7f883c23c9dadd99c27ea82d20a80d5a to your computer and use it in GitHub Desktop.
Rotate images based on EXIF
from PIL import Image, ImageOps
import sys
import glob
import os
import piexif
if len(sys.argv) != 3:
print("usage: rotate.py [input-dir] [output-dir]")
exit(1)
inputDir = os.path.normpath(sys.argv[1])
outputDir = os.path.normpath(sys.argv[2])
print(f"inputDir: {inputDir}\noutput: {outputDir}")
for filepath in glob.iglob(inputDir+"/**/*.jpg", recursive=True):
try:
outputPath = outputDir + filepath[len(inputDir):]
if os.path.isfile(outputPath):
print(f"already exists {outputPath}")
continue
print(f"saving {outputPath}")
image = Image.open(filepath)
exif_dict = piexif.load(image.info["exif"])
if piexif.ImageIFD.Orientation in exif_dict["0th"]:
exif_dict["0th"].pop(piexif.ImageIFD.Orientation)
exif_bytes = piexif.dump(exif_dict)
image = ImageOps.exif_transpose(image)
os.makedirs(os.path.dirname(outputPath), exist_ok=True)
image.save(outputPath, exif=exif_bytes)
image.close()
except Exception as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment