- 1 year ago
Image rotation through entire directory?
To rotate images through an entire directory using Python, you can utilize the PIL
(Pillow) library, which provides a powerful set of image processing functions. Here's an example script:
pythonfrom PIL import Image
import os
def rotate_images_in_directory(directory, degrees):
for filename in os.listdir(directory):
if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
image_path = os.path.join(directory, filename)
try:
image = Image.open(image_path)
rotated_image = image.rotate(degrees, expand=True)
rotated_image.save(image_path)
print(f"Rotated {filename} successfully.")
except Exception as e:
print(f"Failed to rotate {filename}: {str(e)}")
# Example usage: rotate images in the "images" directory by 90 degrees
rotate_images_in_directory("images", 90)
In this script, rotate_images_in_directory
is a function that takes the directory path and the number of degrees to rotate as input. It iterates through each file in the directory and checks if it has a .jpg
, .jpeg
, or .png
extension. If it does, the script opens the image, rotates it by the specified degrees, saves the rotated image over the original image file, and prints a success message. If any error occurs during the rotation process, it prints a failure message.
Make sure to install the Pillow
library (pip install Pillow
) before running the script.
Note: It's recommended to make a backup of your images before running the script, as it modifies the original files.