1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import os
from PIL import Image
def resize_image(input_path, new_width, new_height):
image = Image.open(input_path)
width, height = image.size
aspect_ratio = width / height
if new_width is None:
new_width = int(new_height * aspect_ratio)
elif new_height is None:
new_height = int(new_width / aspect_ratio)
resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
resized_image.save(input_path)
def resize_images_in_directory(directory, new_width, new_height):
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
input_path = os.path.join(root, filename)
resize_image(input_path, new_width, new_height)
if __name__ == "__main__":
target_directory = "your_directory_path"
new_width = 800
new_height = None
resize_images_in_directory(target_directory, new_width, new_height)
|