-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
54 lines (45 loc) · 1.74 KB
/
main.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
import os
from tkinter import filedialog, Tk
from PIL import Image
# Ask the user to select a directory
root = Tk()
root.withdraw()
folder_path = filedialog.askdirectory()
# Define output directory
output_dir = os.path.join(folder_path, "chopped")
# Check if output directory already exists, and increment number if it does
if os.path.isdir(output_dir):
count = 1
while True:
new_dir = output_dir + str(count)
if os.path.isdir(new_dir):
count += 1
else:
output_dir = new_dir
break
# Create output directory
os.makedirs(output_dir)
# Loop through all png and webp files in input directory
for filename in os.listdir(folder_path):
if filename.endswith(".png") or filename.endswith(".webm"):
# Open the image and get its size and aspect ratio
img = Image.open(os.path.join(folder_path, filename))
width, height = img.size
img_aspect_ratio = round(float(width) / float(height), 2)
# Calculate dimensions of 4 images based on aspect ratio
new_width = int(width / 2)
new_height = int(new_width / img_aspect_ratio)
# Crop the image and save 4 new images
for i in range(4):
if i == 0:
box = (0, 0, new_width, new_height)
elif i == 1:
box = (new_width, 0, width, new_height)
elif i == 2:
box = (0, new_height, new_width, height)
elif i == 3:
box = (new_width, new_height, width, height)
img_crop = img.crop(box)
new_filename = os.path.splitext(filename)[0] + str(i + 1) + os.path.splitext(filename)[1]
img_crop.save(os.path.join(output_dir, new_filename))
print("Done chopping files.")