-
Notifications
You must be signed in to change notification settings - Fork 0
/
Image Optimization and Conversion.py
643 lines (540 loc) · 20.4 KB
/
Image Optimization and Conversion.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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#!/usr/bin/env python3
# 🧶 Modules Imports
# Try following pep8 (https://pep8.org/) and try using "black"
# as the default formatter.
# In this case, use Snake case with the first letter of each word
# capitalized. Lowecase for imports and classes only.
import re
import os
import time
import pathlib
import platform
import subprocess
import shutil
import PIL
import tkinter as tkCore
from PIL import Image
from pathlib import Path
from SNL import nick_logger as nick_log
from tkinter.filedialog import askdirectory
from tkinter import (
Tk,
Canvas,
Button,
messagebox,
IntVar,
StringVar,
END,
Listbox,
PhotoImage,
Entry,
Checkbutton,
)
""" Made by Nicolas Mendes - September 2021
SUMMARY:
🧶 Modules Imports
✍️ Initial Setup to load assets
🧝🏻♀️ Tk Window Settings
💬 Variables
=========== Platform OS patches
🌈 UI
=========== Buttons and Labels
=========== Make magic button
=========== Browse Button
=========== Entry to load files
=========== Listbox to show files loaded Root_Window
=========== Logo Text
=========== Checkbox
=========== Logo Icon
🔖 Load GUI files defs
⚙️ Logic and Defs
=========== 📜 Check Function
=========== 🧬 Optimization Functions
=========== 🎭 Convertion Functions
🙌 __main__
"""
# ✍️ Initial Setup to load assets
Log_Routine_Controller = nick_log.log_routine_controller(
False, True, "ioc", 700, True, True, True, "v1.1.0 - Release"
)
OS_Detector = platform.system()
OUTPUT_PATH = pathlib.Path(__file__).parent.absolute()
ASSETS_PATH = OUTPUT_PATH / Path("./Resources")
# If images folfder does not exist, create it.
if not os.path.exists(OUTPUT_PATH / Path("./images")):
os.makedirs(OUTPUT_PATH / Path("./images"))
Images_PATH = OUTPUT_PATH / Path("./images")
def Relative_To_Assets(path: str) -> Path:
"""Return a path relative to the assets folder."""
nick_log.log_routine(
f"[WARNING] Assets folder have been accessed.\n|--------------------------------> [OK] {path} has been loaded."
)
return ASSETS_PATH / Path(path)
def Relative_To_Images(path: str) -> Path:
"""Return a path relative to the images folder."""
nick_log.log_routine(
f"[WARNING] Images folder path have been accessed.\n|--------------------------------> [OK] {path} has been loaded."
)
return Images_PATH / Path(path)
nick_log.log_routine(
nick_log.log_os_details(),
False,
)
try:
# 🧝🏻♀️ Tk Window Settings
Root_Window = Tk()
Root_Window.resizable(False, False)
Root_Window.geometry("980x580")
Root_Window.configure(bg="#151515")
Root_Window.title("Image Optimization and Conversion")
if OS_Detector == "Windows" or OS_Detector == "Darwin":
Root_Window.iconbitmap(Relative_To_Assets("icon.ico"))
# 💬 Variables
files = os.listdir(Images_PATH)
Printable_Files = Images_PATH
# LINUX/BSD/WINDOWS PATCHES
if OS_Detector == "Linux" or OS_Detector == "BSD" or OS_Detector == "FreeBSD" or OS_Detector == "NomadBSD":
# Libre Nix (Tested under Ubuntu, PopOS, Fedora and NomadBSD)
Select_Folder_Font_Size = 12
List_X_Position = 0.59
List_Y_Position = 0.5
IOC_Type_Size = 24
Checkbox_Label_Size = 9
Checkbox_X_Position=0.031
Checkbox_Y_Position=0.71
List_Height = 5
List_Width = 50
elif OS_Detector == "Windows":
# Windows 10+
Select_Folder_Font_Size = 18
List_X_Position = 0.59
List_Y_Position = 0.65
IOC_Type_Size = 36
Checkbox_Label_Size = 12
Checkbox_X_Position=0.032
Checkbox_Y_Position=0.71
List_Height = 15
List_Width = 75
else:
# Works well on MacOS Darwin (High Sierra+).
Select_Folder_Font_Size = 18
List_X_Position = 0.5
List_Y_Position = 0.5
IOC_Type_Size = 36
Checkbox_Label_Size = 13
Checkbox_X_Position=0.03
Checkbox_Y_Position=0.7
List_Height = 5
List_Width = 50
# 🌈 UI
canvas = Canvas(
Root_Window,
bg="#151515",
height=580,
width=980,
bd=0,
highlightthickness=0,
relief="ridge",
)
# Buttons and Labels
canvas.place(x=0, y=0)
image_image_1 = PhotoImage(file=Relative_To_Assets("image_1.png"))
image_1 = canvas.create_image(95.0, 290.0, image=image_image_1)
# Make magic button ( Aka optimizing and conversion functions )
button_image_1 = PhotoImage(file=Relative_To_Assets("button_1.png"))
button_1 = Button(
image=button_image_1,
borderwidth=0,
highlightthickness=0,
command=lambda: optimizationFunction(),
relief="flat",
)
button_1.place(x=28.0, y=502.0, width=135.0, height=46.0)
image_image_2 = PhotoImage(file=Relative_To_Assets("image_2.png"))
image_2 = canvas.create_image(577.0, 348.0, image=image_image_2)
image_image_3 = PhotoImage(file=Relative_To_Assets("image_3.png"))
image_3 = canvas.create_image(577.0, 64.0, image=image_image_3)
# Browse Button ( Aka selecting files )
button_image_2 = PhotoImage(file=Relative_To_Assets("button_2.png"))
button_2 = Button(
image=button_image_2,
borderwidth=0,
highlightthickness=0,
command=lambda: Load_Folder_For_Img(),
relief="flat",
)
button_2.place(x=812.0, y=41.0, width=135.0, height=46.0)
# 🔖 Load GUI files defs
def Load_Folder_For_Img():
"""Load the folder with images"""
global Images_PATH
global entry_DefPath
global files
global Printable_Files
# open dialog box to select folder
Printable_Files = askdirectory(initialdir=Images_PATH)
# If the user cancel it will fallback to the default folder.
if Printable_Files == "" or Printable_Files == " ":
Printable_Files = Images_PATH
entry_DefPath.set(str(Images_PATH))
else:
entry_DefPath.set(str(Printable_Files))
# Regular expression to pick all words after the last "/".
# Folder_Imgs = re.findall(r"[^\\\/]+$", Printable_Files)
nick_log.log_routine(
f"inside loadFolderForImg: {Printable_Files}, {entry_DefPath.get()} and {entry_1.get()}"
)
Images_PATH = Path(f"{Printable_Files}")
files = os.listdir(Images_PATH)
Quick_Update_List()
# Entry to load files
entry_DefPath = StringVar()
entry_DefPath.set(str(Images_PATH))
entry_image_1 = PhotoImage(file=Relative_To_Assets("entry_1.png"))
entry_bg_1 = canvas.create_image(567.5, 74.0, image=entry_image_1)
entry_1 = Entry(
bd=0,
bg="#2D2D2D",
fg="#FFFFFF",
disabledbackground="#2D2D2D",
disabledforeground="#FFFFFF",
textvariable=entry_DefPath,
highlightthickness=0,
state="disabled",
)
entry_1.place(x=364.0, y=41.0, width=407.0, height=44.0)
# Dummy label ( Don't touch )
canvas.create_text(
210.0,
53.0,
anchor="nw",
text="Select Folder",
fill="#FFFFFF",
font=("Mulish Regular", Select_Folder_Font_Size * -1),
)
# Listbox to show files loaded Root_Window
list_items = Listbox(
x=210.0,
y=115.0,
height=List_Height,
width=List_Width,
bg="#232323",
fg="#FFFFFF",
font=("Mulish Regular", 18 * -1),
highlightcolor="#ECC0FB",
border=0,
highlightthickness=0,
borderwidth=0,
)
list_items.place(relx=List_X_Position, rely=List_Y_Position, anchor="center")
canvas.create_text(
253.0,
155.0,
anchor="nw",
text="Images found inside the folder",
fill="#FFFFFF",
font=("Mulish Regular", 16 * -1),
)
image_image_4 = PhotoImage(file=Relative_To_Assets("image_4.png"))
image_4 = canvas.create_image(226.0, 165.0, image=image_image_4)
# Logo text ( Don't touch )
canvas.create_text(
58.0,
114.0,
anchor="nw",
text="I.O.C",
fill="#FFFFFF",
font=("Mulish Bold", IOC_Type_Size * -1),
)
# Checkbox (To reduce resolution by half)
Reduce_By_Half = IntVar()
Reduce_By_HalfChck = Checkbutton(
text="Smart Scale Mode",
variable=Reduce_By_Half,
bg="#AC59F3",
fg="#FFFFFF",
font=("Mulish Regular", Checkbox_Label_Size * -1),
)
Reduce_By_HalfChck.deselect()
Reduce_By_HalfChck.place(relx=Checkbox_X_Position, rely=Checkbox_Y_Position, anchor="nw")
# Logo Icon
image_image_6 = PhotoImage(file=Relative_To_Assets("image_6.png"))
image_6 = canvas.create_image(95.0, 64.0, image=image_image_6)
# ⚙️ Logic and Defs
"""
Optimization and Convertion Scripts forked from my Python Fundamentals Study GitHub repository.
Forked on September 23, 2021.
https://github.com/DreamDevourer/Python-Fundamentals-Study
"""
def Cleaning_Routine():
"""Removes any legacy image"""
nick_log.log_routine("Beginning cleaning routine")
for file in files:
File_Name = re.sub(r"\s+|\d|\(|\)", "_", file)
if (
File_Name.endswith(".png")
or File_Name.endswith(".jpg")
or File_Name.endswith(".jpeg")
or File_Name.endswith(".gif")
):
# Delete original file
nick_log.log_routine(f"Deleting {File_Name}")
os.remove(f"{Folder_Imgs}/{File_Name}")
# =========== 📜 Check Function ===========
Folder_Imgs = entry_1.get()
def Quick_Update_List():
"""Refresh the list quicker."""
global files
files = None
files = os.listdir(Images_PATH)
time.sleep(0.5)
list_items.delete(0, END)
for file in files:
if (
file.endswith(".png")
or file.endswith(".jpg")
or file.endswith(".jpeg")
or file.endswith(".gif")
):
list_items.insert(END, file)
if file.endswith(".webp") and "Optimized" not in file:
list_items.insert(END, file)
def Scheduler_Controller():
"""Function to execute tasks in X ms."""
Quick_Update_List()
Root_Window.after(2000, Scheduler_Controller)
def Update_Listbox():
"""Update the list box with all files found in the folder"""
global files
global Folder_Imgs
Folder_Imgs = entry_1.get()
# check if backup folder exists inside images folder
if not os.path.exists(f"{Folder_Imgs}/backup"):
os.mkdir(f"{Folder_Imgs}/backup")
nick_log.log_routine("[OK] Backup folder created.")
Update_Files_Found = os.listdir(Images_PATH)
files = Update_Files_Found
list_items.delete(0, END)
for file in files:
# regular expression to replace spaces to underlines and remove any digits.
File_Name = re.sub(r"\s+|\d|\(|\)", "_", file)
if (
file.endswith(".png")
or file.endswith(".jpg")
or file.endswith(".jpeg")
or file.endswith(".gif")
):
# rename all files to replace spaces to underlines.
os.rename(
os.path.join(Folder_Imgs, file),
os.path.join(Folder_Imgs, File_Name),
)
list_items.insert(END, File_Name)
nick_log.log_routine(
f"[OK] Found valid images in {Folder_Imgs} with {file}."
)
if file.endswith(".webp") and "Optimized" not in file:
November_File_Name = file.replace(".webp", "")
Oscar_File_Name = re.sub(r"\_[_][_]|\_|\_[_]", " ", November_File_Name)
Oscar_File_Name = re.sub(r"^\s+|\s+$", "", Oscar_File_Name)
nick_log.log_routine(f"Renaming {file} to {Oscar_File_Name}")
if Oscar_File_Name == " " or Oscar_File_Name == "":
os.rename(
f"{Folder_Imgs}/{file}",
f"{Folder_Imgs}/Optimized {len(Oscar_File_Name)}.webp",
)
else:
os.rename(
f"{Folder_Imgs}/{file}",
f"{Folder_Imgs}/Optimized {Oscar_File_Name}.webp",
)
Quick_Update_List()
# =========== 🧬 Optimization Functions ===========
def optimizationFunction():
"""Optimization function to reduce the resolution of the images and remove images bloatware."""
global Reduce_By_Half
global files
nick_log.log_routine(
f"These are all of the files in our current working directory: {files}"
)
Confirm_Down_Res = IntVar()
Confirm_Down_Res = Reduce_By_Half.get()
# check if backup folder exists inside images folder
if not os.path.exists(f"{Folder_Imgs}/backup"):
os.mkdir(f"{Folder_Imgs}/backup")
nick_log.log_routine("[OK] Backup folder created.")
Update_Listbox()
for file in files:
File_Name = re.sub(r"\s+|\d|\(|\)", "_", file)
if (
file.endswith(".png")
or file.endswith(".jpg")
or file.endswith(".jpeg")
or file.endswith(".gif")
):
nick_log.log_routine(f"[OK] Renamed {file} to {File_Name}")
# Backup operation
shutil.copy(
f"{Folder_Imgs}/{File_Name}",
f"{Folder_Imgs}/backup/_backup_{File_Name}",
)
nick_log.log_routine(f"Copying {File_Name} to backup folder")
nick_log.log_routine(f"Optimizing {File_Name}")
Img_Optimize = Image.open(Relative_To_Images(str(File_Name)))
imgWidth, imgHeight = Img_Optimize.size
nick_log.log_routine(f"Image size: {imgWidth} x {imgHeight}")
nick_log.log_routine(
f"The state of resolution option is: {Confirm_Down_Res}"
)
list_items.delete(0, END)
list_items.insert(END, File_Name)
# If Confirm_Down_Res = 1, imgWidth and imgHeight are larger than 1366x768 reduce the resolution by half.
if (
(imgWidth > 1366 and imgHeight > 768)
or (imgWidth > 1400 and imgHeight > 1400)
and Confirm_Down_Res == 1
):
Img_Optimize = Img_Optimize.resize(
(int(imgWidth / 2), int(imgHeight / 2)), PIL.Image.ANTIALIAS
)
nick_log.log_routine(
f"Reducing image resolution by half of {File_Name}"
)
nick_log.log_routine(f"[OK] Optimized {File_Name}")
if file.endswith(".png"):
Img_Optimize.save(
str(Relative_To_Images(str(File_Name))),
optimize=True,
quality=70,
)
if (
file.endswith(".jpg")
or file.endswith(".jpeg")
or file.endswith(".gif")
):
Img_Optimize.save(
str(Relative_To_Images(str(File_Name))),
optimize=True,
quality=80,
)
# If user don't want to reduce image resolution by half.
else:
nick_log.log_routine(
f"Image: {File_Name}, is not larger enough to reduce resolution."
)
nick_log.log_routine(
f"Performing standard optimization on {File_Name}"
)
if File_Name.endswith(".png"):
Img_Optimize.save(
str(Relative_To_Images(str(File_Name))),
optimize=True,
quality=70,
)
if (
File_Name.endswith(".jpg")
or File_Name.endswith(".jpeg")
or File_Name.endswith(".gif")
):
Img_Optimize.save(
str(Relative_To_Images(str(File_Name))),
optimize=True,
quality=80,
)
nick_log.log_routine(f"[OK] {File_Name} optimized!")
else:
nick_log.log_routine(
f"No valid files found in {Folder_Imgs} with {File_Name}... Checking again."
)
Convertion_Function()
Update_Listbox()
# =========== 🎭 Convertion Functions ===========
def Convertion_Function():
"""Convert all images to webp format."""
nick_log.log_routine(
f"These are all of the files in our current working directory: {files}"
)
for file in files:
File_Name = re.sub(r"\s+|\d|\(|\)", "_", file)
if (
File_Name.endswith(".png")
or File_Name.endswith(".jpg")
or File_Name.endswith(".jpeg")
or File_Name.endswith(".gif")
):
nick_log.log_routine(f"Converting {File_Name} to WebP")
Load_Img = Image.open(Relative_To_Images(str(File_Name)))
# remove ".png", ".jpg", ".jpeg", ".gif" from File_Name
if File_Name.endswith(".png"):
Delta_File_Name = File_Name.replace(".png", "")
elif File_Name.endswith(".jpg"):
Delta_File_Name = File_Name.replace(".jpg", "")
elif File_Name.endswith(".jpeg"):
Delta_File_Name = File_Name.replace(".jpeg", "")
elif File_Name.endswith(".gif"):
Delta_File_Name = File_Name.replace(".gif", "")
Load_Img.save(
str(Relative_To_Images(str(Delta_File_Name))) + ".webp",
"WEBP",
quality=80,
)
nick_log.log_routine(f"[OK] {File_Name} converted to WebP")
else:
nick_log.log_routine(f"{File_Name} is not a eligible, skipping...")
# Show a message window with "Optimization and conversion completed!"
Cleaning_Routine()
if OS_Detector == "Darwin":
subprocess.Popen(["open", "-R", Folder_Imgs])
elif OS_Detector == "Windows":
subprocess.Popen(["explorer", Folder_Imgs])
elif (
(OS_Detector == "Linux")
or (OS_Detector == "FreeBSD")
or (OS_Detector == "NomadBSD")
or (OS_Detector == "BSD")
):
subprocess.Popen(["xdg-open", Folder_Imgs])
messagebox.showinfo(
title="Optimization and conversion completed! \n",
message="All files have been optimized and converted to WebP!",
icon="info",
)
nick_log.log_routine("[OK] Images optimized! Starting to update list.")
Quick_Update_List()
except (
RuntimeError,
TypeError,
NameError,
FileNotFoundError,
OSError,
tkCore.TclError,
AttributeError,
) as eM:
nick_log.log_routine(f"[X] ERROR: {eM}", False)
messagebox.showerror(
title="Error",
message="Check the log for details.",
icon="error",
)
except Exception as eFatal:
nick_log.log_routine(f"[X] FATAL ERROR: {eFatal}")
except:
nick_log.log_routine("[X] FATAL ERROR: Unknown error!")
# 🙌 __main__
if __name__ == "__main__":
if (
OS_Detector == "Linux"
or OS_Detector == "Darwin"
or OS_Detector == "BSD"
or OS_Detector == "FreeBSD"
or OS_Detector == "NomadBSD"
or OS_Detector == "Windows"
):
nick_log.log_routine(
"[OK] IOC has started!\n===========PROGRAM INITIATED===========\n"
)
if OS_Detector == "Windows" or OS_Detector == "Darwin":
Root_Window.after(500, Scheduler_Controller)
Root_Window.mainloop()
else:
nick_log.log_routine(f"[X] ERROR: OS {OS_Detector} NOT OFFICIALLY SUPPORTED")