-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBatchImageResizer.pyw
231 lines (210 loc) · 9.39 KB
/
BatchImageResizer.pyw
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#!python3
# -*- coding: utf-8 -*-
#author: [email protected]
import os
import sys
import time
import shutil
from threading import Event
from PIL import Image
from typing import (Any, Callable, Dict, List, Sequence, Tuple)
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
from tkasyncframe import AsyncFrame, WidgetUtil
RESIZE_NOTIFY_ID = 1
ImgMode = {
'.png': 'RGBA',
'.jpg': 'RGB',
'.tiff': 'RGB',
'.bmp': 'RGB',
'.gif': 'P',
}
class MainFrame(AsyncFrame, WidgetUtil):
def __init__(self, parent):
super().__init__(parent)
self.started = False
self.stop_event = Event()
self.src_path_var = tk.StringVar()
self.dst_path_var = tk.StringVar()
self.src_ext_var = tk.StringVar()
self.src_ext_var.set('.jpg .jpeg .png .bmp .tif .tiff')
self.dst_ext_var = tk.StringVar()
self.dst_ext_var.set('.png')
self.clip_var = tk.StringVar()
self.clip_var.set('0,0,0,0')
self.side_var = tk.StringVar()
self.side_var.set(1920)
self.rotate_var = tk.StringVar()
self.rotate_var.set('0')
self.flip_left_right_var = tk.BooleanVar()
self.flip_top_bottom_var = tk.BooleanVar()
script_dir = os.path.dirname(__file__)
if script_dir:
os.chdir(script_dir)
self.pack(expand=True, fill=tk.BOTH)
self.init_ui()
self.master.protocol("WM_DELETE_WINDOW", self.close)
def init_ui(self):
self.master.title('Batch Image Resizer by yinkaisheng')
self.pack(fill=tk.BOTH, expand=1)
self.centerWindow(720, 0.5)
self.master.minsize(600, 400)
src_frame = ttk.Frame(self)
src_frame.pack(side=tk.TOP, fill=tk.X, padx=4, pady=4)
src_label = ttk.Label(src_frame, text='Pictures Folder:')
src_label.pack(side=tk.LEFT)
self.open_btn = ttk.Button(src_frame, text='Open...', command=self.on_click_open)
self.open_btn.pack(side=tk.RIGHT)
self.src_path_entry = ttk.Entry(src_frame, textvariable=self.src_path_var)
self.src_path_entry.pack(fill=tk.X, expand=1, padx=4)
dst_frame = ttk.Frame(self)
dst_frame.pack(side=tk.TOP, fill=tk.X, padx=4, pady=4)
dst_label = ttk.Label(dst_frame, text='Output Folder: ')
dst_label.pack(side=tk.LEFT)
self.start_btn = ttk.Button(dst_frame, text='Start', command=self.on_click_start)
self.start_btn.pack(side=tk.RIGHT)
self.dst_path_entry = ttk.Entry(dst_frame, textvariable=self.dst_path_var)
self.dst_path_entry.pack(fill=tk.X, expand=1, padx=4)
format_frame = ttk.Frame(self)
format_frame.pack(side=tk.TOP, fill=tk.X, padx=4, pady=4)
src_ext_label = ttk.Label(format_frame, text='Only Convert the Following Formats:')
src_ext_label.pack(side=tk.LEFT)
self.ext_entry = ttk.Entry(format_frame, textvariable=self.src_ext_var, width=30)
self.ext_entry.pack(side=tk.LEFT)
dst_ext_label = ttk.Label(format_frame, text=' Output Format:')
dst_ext_label.pack(side=tk.LEFT)
self.dst_ext_combo = ttk.Combobox(format_frame, textvariable=self.dst_ext_var, state='readonly', width=10)
self.dst_ext_combo['values'] = ['.png', '.jpg', '.gif', '.tiff', '.bmp', 'No Change']
self.dst_ext_combo.pack(side=tk.LEFT)
transform_frame = ttk.Frame(self)
transform_frame.pack(side=tk.TOP, fill=tk.X, padx=4, pady=4)
clip_label = ttk.Label(transform_frame, text='clip l,t,r,b:')
clip_label.pack(side=tk.LEFT)
self.clip_entry = ttk.Entry(transform_frame, textvariable=self.clip_var, width=14)
self.clip_entry.pack(side=tk.LEFT)
size_label = ttk.Label(transform_frame, text=' Max Width or Height:')
size_label.pack(side=tk.LEFT)
self.side_entry = ttk.Entry(transform_frame, textvariable=self.side_var, width=6)
self.side_entry.pack(side=tk.LEFT)
rotate_label = ttk.Label(transform_frame, text=' Rotate:')
rotate_label.pack(side=tk.LEFT)
self.rotate_combo = ttk.Combobox(transform_frame, textvariable=self.rotate_var, state='readonly', width=4)
self.rotate_combo['values'] = ['0', '90', '180', '270']
self.rotate_combo.pack(side=tk.LEFT)
self.flip_lr_check = ttk.Checkbutton(transform_frame, text='Horizontal Flip', variable=self.flip_left_right_var)
self.flip_lr_check.pack(side=tk.LEFT, padx=4)
self.flip_tb_check = ttk.Checkbutton(transform_frame, text='Vertical Flip', variable=self.flip_top_bottom_var)
self.flip_tb_check.pack(side=tk.LEFT, padx=4)
ttk.Label(self, text='Output:').pack(side=tk.TOP)
self.output_entry = ScrolledText(self, wrap=tk.WORD)
self.output_entry.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def close(self):
self.master.destroy()
def on_click_open(self):
imgdir = filedialog.askdirectory()
if imgdir:
self.src_path_var.set(imgdir)
self.dst_path_var.set(imgdir + '_resized_output')
def on_click_start(self):
if not self.started:
src_path = self.src_path_var.get()
dst_path = self.dst_path_var.get()
if not os.path.exists(src_path):
return
if not os.path.exists(dst_path):
os.makedirs(dst_path)
clips = self.clip_var.get().split(',')
if len(clips) == 4:
try:
clips = tuple(int(it) for it in clips)
except:
clips = (0, 0, 0, 0)
else:
clips = (0, 0, 0, 0)
max_side = int(self.side_var.get())
src_exts = self.src_ext_var.get()
dst_ext = self.dst_ext_var.get()
rotate = int(self.rotate_var.get())
flip_lr = self.flip_left_right_var.get()
flip_tb = self.flip_top_bottom_var.get()
self.runInThread(self.convert_func, (self.stop_event, src_path, dst_path, src_exts, dst_ext, clips, max_side, rotate, flip_lr, flip_tb), self.convert_notify)
self.start_btn.config(text='Stop')
self.started = True
self.clearEntry(self.output_entry)
else:
self.stop_event.set()
def convert_notify(self, thread_id: int, notify_id: int, args: Any):
if notify_id == RESIZE_NOTIFY_ID:
self.appendEntryText(self.output_entry, args + '\n')
elif notify_id == AsyncFrame.NotifyID_ThreadExit:
self.start_btn.config(text='Start')
self.appendEntryText(self.output_entry, '----\nDone\n')
self.stop_event.clear()
self.started = False
else:
pass
def convert_func(self, threadId: int, args: Any):
stop_event, src_dir, dst_dir, src_exts, dst_ext, clips, max_side, rotate, flip_lr, flip_tb = args
files = os.listdir(src_dir)
src_exts = src_exts.lower().split()
for it in files:
if stop_event.is_set():
break
name, ext = os.path.splitext(it)
ext = ext.lower()
if ext in src_exts:
if not dst_ext.startswith('.'):
dst_ext = ext
if src_dir == dst_dir:
newfile = name + '_resized' + dst_ext
else:
newfile = name + dst_ext
src_file = os.path.join(src_dir, it)
dst_file = os.path.join(dst_dir, newfile)
w, h, nw, nh = self.resize_image(src_file, ext, dst_file, dst_ext, clips, max_side, rotate, flip_lr, flip_tb)
info = '{}, {}x{} -> {}, {}x{}'.format(it, w, h, newfile, nw, nh)
self.threadNotifyUI(threadId, RESIZE_NOTIFY_ID, info)
def resize_image(self, src_path: int, src_ext: int, dst_path: int, dst_ext: int, clips: Tuple[int, int, int, int],
max_side: int = 1920, rotate: int = 0, flip_lr: bool = False, flip_rb: bool = False):
img = Image.open(src_path)
width, height = img.size
max_src = max(width, height)
if os.path.exists(dst_path):
os.remove(dst_path)
newimg = img
if sum(clips) > 0:
newimg = newimg.crop((clips[0], clips[1], width - clips[2], height - clips[3]))
width, height = newimg.size
if max_src > max_side:
if width > height:
new_width = max_side
new_height = int(height / (width / max_side))
else:
new_height = max_side
new_width = int(width / (height / max_side))
newimg = newimg.resize((new_width, new_height), Image.ANTIALIAS)
else:
new_width, new_height = width, height
if rotate != 0:
newimg = newimg.rotate(rotate, expand=True)
if rotate // 90 % 2 == 1:
new_width, new_height = new_height, new_width
if flip_lr:
newimg = newimg.transpose(Image.FLIP_LEFT_RIGHT)
if flip_rb:
newimg = newimg.transpose(Image.FLIP_TOP_BOTTOM)
if src_ext != dst_ext:
if newimg.mode != ImgMode[dst_ext]:
newimg = newimg.convert(ImgMode[dst_ext])
newimg.save(dst_path)
del img
del newimg
return width, height, new_width, new_height
def main():
root = tk.Tk()
app = MainFrame(root)
root.mainloop()
if __name__ == '__main__':
main()