-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresize.py
64 lines (44 loc) · 1.57 KB
/
resize.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import PIL
import os
from PIL import Image
path = r"C:\Users\lofru\Private Cloud\Pfadi\PfadiAfi\AL\Website\Fotos\01_Uploaded\22\goldi pfila"
max_edge_length = 1000 # define length of longer side in resized image
os.listdir(path)
for file in os.listdir(path):
path_img = os.path.join(path, file)
try:
img = Image.open(path_img)
except:
print("couldnt open file %s" % path_img)
continue
# todo raise exception
# check if image is landscape or portrait
width = img.width
height = img.height
# todo add check if image is actually larger than goal size
ratio = width / height
if (
ratio < 1
): # if ratio is less than 1, it is portrait. if its portrait, the height has to be equal to max_edge_length
edge_ratio = height / max_edge_length
new_height = max_edge_length
new_width = width / edge_ratio
elif (
ratio > 1
): # if ratio is greater than 1, it is landscape. if its landscape, the width has to be equal to max_edge_length
edge_ratio = width / max_edge_length
new_width = max_edge_length
new_height = height / edge_ratio
elif ratio == 1: # catch exact squares
new_width = max_edge_length
new_height = max_edge_length
else:
print("couldnt resize for some reason")
continue
# todo add better error message
# todo raise exception
new_width = round(new_width)
new_height = round(new_height)
img = img.resize((new_width, new_height))
img.save(path_img)
img.close()