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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
|
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
from PIL import Image, ImageTk, ImageOps
from ctypes import windll
import math as maths
import tkFileBrowser
import screeninfo
import webbrowser
import threading
import win32file
import win32api
import shutil
import time
import sys
import os
IMPORT_FILES = ['.png', '.jpg', '.jfif', '.jpg_large', '.gif', ".webp"]
# Not sure what the deal with this is? I swear we never had to do this? Its probably some windows 11 BS
# windll.shell32.SetCurrentProcessExplicitAppUserModelID('sneed.feed.com')
class App(tk.Tk):
last_event_hw = (None, None)
last_event_time = time.time()
def __init__(self, path = None, *args, **kwargs):
"""Main class
Keyword Arguments:
path {str} -- path to the image to open on (default: {None})
"""
tk.Tk.__init__(self)
self.title("EEHPH Photo Viewer v2.3.1")
self.iconbitmap(os.path.join(os.path.dirname(__file__), "Assets", "icon.ico"))
self.geometry("%ix%i" % (max_width(), max_height()))
paned = ttk.Panedwindow(self, orient = tk.HORIZONTAL)
paned.pack(fill = tk.BOTH, expand = True)
self.drive_viewer = EEHPHTree(self, command = lambda a: self.img_viewer.open_image(a), showhidden = True)
paned.add(self.drive_viewer)
self.img_viewer = ImageViewer(self)
paned.add(self.img_viewer)
if path is not None:
if os.path.splitext(path)[1] not in IMPORT_FILES:
messagebox.showerror('Error', 'Invalid file type. EEHPH2 accepts only %s.' % (' ').join(IMPORT_FILES))
else:
self.img_viewer.open_image(path)
#draw menubar
menu = tk.Menu(self)
self.config(menu=menu)
fileMenu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=fileMenu, underline=0)
self.__icon_img = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Assets', 'image.png'))
fileMenu.add_command(label='Open image...', accelerator = "Ctrl+O", image=self.__icon_img, compound=tk.LEFT, command=self.__open)
self.__icon_folder = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Assets', 'folder.png'))
fileMenu.add_command(label='Open folder...', accelerator = "Ctrl+Shift+O", image=self.__icon_folder, compound=tk.LEFT, command=self.__open_folder)
fileMenu.add_separator()
fileMenu.add_command(label='Close', command=self.destroy)
editMenu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Edit', menu=editMenu, underline=0)
self.__icon_clipboard = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Assets', 'clipboard_small.png'))
editMenu.add_command(label='Copy path to clipboard', accelerator = "Ctrl+C", image=self.__icon_clipboard, compound=tk.LEFT, command=self.img_viewer.buttons.clipboard)
self.__icon_save = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Assets', 'save_small.png'))
editMenu.add_command(label='Save image to another location', accelerator = "Ctrl+S", image=self.__icon_save, compound=tk.LEFT, command=self.img_viewer.buttons.save)
editMenu.add_separator()
self.__icon_edit = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(__file__), "Assets", "edit.png")).resize((16, 16)))
editMenu.add_command(label = 'Edit image', accelerator = "Ctrl+E", command = self.img_viewer.edit_image, image = self.__icon_edit, compound = tk.LEFT)
viewMenu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='View', menu=viewMenu, underline=0)
self.__icon_fullscreen = tk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Assets', 'images.png'))
viewMenu.add_command(label='Fullscreen', accelerator = "<Space> / F11", image=self.__icon_fullscreen, compound=tk.LEFT, command=self.img_viewer.buttons.fullscreen)
self.__icon_left = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(__file__), "Assets", "arrow_left.png")).resize((16, 16)))
viewMenu.add_command(label='Previous image', accelerator = "←", image = self.__icon_left, compound = tk.LEFT, command=self.img_viewer.buttons.backwards)
self.__icon_right = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(__file__), "Assets", "arrow_left.png")).resize((16, 16)).rotate(180))
viewMenu.add_command(label='Next image', accelerator = "→", image = self.__icon_right, compound = tk.LEFT, command=self.img_viewer.buttons.forwards)
imageMenu = tk.Menu(menu, tearoff = 0)
menu.add_cascade(label = "Image", menu = imageMenu, underline = 0)
self.__icon_clockwise = ImageTk.PhotoImage(ImageOps.mirror(Image.open(os.path.join(os.path.dirname(__file__), "Assets", "rotate_right.png")).resize((16, 16))))
imageMenu.add_command(label='Rotate 90° clockwise', accelerator = "R", image = self.__icon_clockwise, compound = tk.LEFT, command=self.img_viewer.buttons.clockwise)
self.__icon_anticlockwise = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(__file__), "Assets", "rotate_right.png")).resize((16, 16)))
imageMenu.add_command(label='Rotate 90° anticlockwise', accelerator = "Shift+R", image = self.__icon_anticlockwise, compound = tk.LEFT, command=self.img_viewer.buttons.anticlockwise)
self.__icon_flip = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(__file__), "Assets", "flip.png")).resize((16, 16)))
imageMenu.add_command(label='Flip image', accelerator = "F", image = self.__icon_flip, compound = tk.LEFT, command=self.img_viewer.buttons.flip)
menu.add_command(label = "Source", underline = 0, command = lambda: webbrowser.open_new("https://github.com/jwansek/eehph2"))
self.new_state = "normal"
self.bind('<Left>', self.img_viewer.buttons.backwards)
self.bind('<Right>', self.img_viewer.buttons.forwards)
self.bind('<space>', self.img_viewer.buttons.fullscreen)
self.bind('<F11>', self.img_viewer.buttons.fullscreen)
self.bind('<Control-c>', self.img_viewer.buttons.clipboard)
self.bind('<Control-s>', self.img_viewer.buttons.save)
self.bind('<Control-o>', self.__open)
self.bind('<Control-O>', self.__open_folder)
self.bind('<r>', self.img_viewer.buttons.clockwise)
self.bind('<R>', self.img_viewer.buttons.anticlockwise)
self.bind('<f>', self.img_viewer.buttons.flip)
self.bind('<Control-e>', self.img_viewer.edit_image)
self.bind('<F5>', self.refresh)
self.bind('<Configure>', self.__on_config)
def __on_config(self, event = None):
"""Event for when the app is resized.
Keyword Arguments:
event {event} -- Done to make the app work with events (default: {None})
"""
# only refresh if the window is resized, and a certain amount of time has passed since the last refresh. so we don't slow down the computer
# this perhaps causes too many screen flashes? this number could do with tuning. (photosensative sensory issues beware!)
# print(time.time(), event, type(event.widget) is App)
if ((event.height, event.width) != self.last_event_hw) and (time.time() - self.last_event_time >= 0.025) and (type(event.widget) is App):
# print("Resized", time.time() - self.last_event_time)
self.last_event_time = time.time()
self.refresh()
self.last_event_hw = (event.height, event.width)
# self.old_state = self.new_state # assign the old state value
# self.new_state = self.state() # get the new state value
# if self.new_state == 'zoomed':
# #maximise event
# self.refresh()
# elif self.new_state == 'normal' and self.old_state == 'zoomed':
# #restore event
# self.refresh()
def refresh(self, event = None):
"""Reloads the current image.
Done so the image is resized when the app is resized.
Keyword Arguments:
event {event} -- Used to make the method work with events. (default: {None})
"""
if self.img_viewer.path is not None:
self.img_viewer.open_image(self.img_viewer.path)
def __open(self, event=None):
"""Private. Used to open an image asking the user where
they want to open an image from. Then calls the img_viewer
class.
Keyword Arguments:
event {event} -- Unused. Used to make the method
work with events (default: {None})
"""
filetypes = get_filetypes()
path = filedialog.askopenfilename(filetypes=filetypes)
if path != '' or path == None:
self.img_viewer.open_image(path)
def __open_folder(self, event=None):
"""Opens a folder from disk by opening a file from it.
Checks allowed files are present first
Keyword Arguments:
event {event} -- Unused. Used to make the method
work with events (default: {None})
"""
path = filedialog.askdirectory()
files = []
if path != '' or path == None:
for file in os.listdir(path):
if os.path.splitext(file)[1].lower() in IMPORT_FILES:
files.append(file)
if files != []:
self.img_viewer.open_image(os.path.join(path, files[0]))
else:
messagebox.showwarning('', 'There are no avaliable file types in the folder. Accepts %s.' % (' ').join(IMPORT_FILES))
class EEHPHTree(tkFileBrowser.TkFileBrowser):
def __init__(self, parent, command, *args, **kwargs):
super().__init__(parent = parent, command = command, refresh = int(9e9), rightclick_options = [], *args, **kwargs)
def refresh(self):
"""
Override this method to do nothing, since we don't need this feature and at the moment it is rather buggy.
"""
pass
class ImageViewer(tk.Frame):
orig_dims = None
dims = None
path = None
large_img = None
def __init__(self, parent):
"""Class to show images on screen. Resizes images
appropopriately so it fits on the screen.
Arguments:
parent {object} -- class that called this
"""
tk.Frame.__init__(self, parent)
self.parent = parent
self.focus_set()
self.lbl_img = tk.Label(self, text = "No image selected")
self.lbl_img.pack(fill = tk.BOTH, expand = True)
self.buttons = Buttons(self)
self.buttons.pack()
def open_image(self, path):
"""Changes the label to show 'loading' and starts a loading thread.
Arguments:
path {str} -- path of image to open
"""
self.lbl_img.config(image = "", text = "Loading...")
print(path)
self.parent.drive_viewer.see(path)
threading.Thread(target = self.__open, args = (path, )).start()
def __open(self, arg):
"""Private. Actually open an image. Work out an appropriate size and show on screen.
Arguments:
arg {str/Image} -- str of path to open or Image object to show
_ {N/A} -- Unused. Required for some reason since apparently threading.Thread() requires at least two
args or weird stuff starts happenning.
"""
if type(arg) is str:
self.path = arg
img = Image.open(self.path)
else:
img = arg
self.orig_dims = img.size
self.lbl_img.focus_set() #focus this so using the arrow keys doesn't mess up the treeview
self.large_img = img
treewidth = self.parent.drive_viewer.winfo_width()
appwidth = self.parent.winfo_width()
appheight = self.parent.winfo_height()
btnsheight = self.buttons.winfo_height()
imgwidth = img.size[0]
imgheight = img.size[1]
maxwidth = appwidth - (treewidth + 10)
maxheight = appheight - (btnsheight + 10)
print(maxwidth, maxheight)
#image is too big in both directions
#https://stackoverflow.com/questions/6565703/math-algorithm-fit-image-to-screen-retain-aspect-ratio
if imgwidth > maxwidth and imgheight > maxheight:
if (maxwidth/maxheight) > (imgwidth/imgheight):
img = img.resize((int(imgwidth * maxheight / imgheight) - 5, maxheight - 5))
else:
img = img.resize((maxwidth, int(imgheight * maxwidth / imgwidth)))
#image is too wide
if img.size[0] > maxwidth:
img = self.resize(img, width = maxwidth)
#image is too taall
if img.size[1] > maxheight:
img = self.resize(img, height = maxheight)
#display
dims = img.size
tkimg = ImageTk.PhotoImage(image = img)
self.lbl_img.config(image = tkimg)
self.lbl_img.image = tkimg
#update label
text = "%-56s %s (%ix%i)" % (os.path.split(self.path)[-1:][0], str(int((img.size[0] / self.orig_dims[0]) * 100)) + "%", self.orig_dims[0], self.orig_dims[1])
self.buttons.lbl_text.config(text = text)
#unused
def resize(self, img, **kwargs):
if list(kwargs.keys())[0] == 'height':
baseheight = kwargs['height']
hpercent = baseheight / float(img.size[1])
wsize = int(float(img.size[0]) * float(hpercent))
return img.resize((wsize, baseheight))
elif list(kwargs.keys())[0] == 'width':
basewidth = kwargs['width']
wpercent = basewidth / float(img.size[0])
hsize = int(float(img.size[1]) * float(wpercent))
return img.resize((basewidth, hsize))
raise TypeError("Missing argument: must have 'height' or 'width'.")
def edit_image(self, event = None):
"""Event placeholder to edit an image. Calls the EditWindow()
class.
Keyword Arguments:
event {event} -- Used to make the method work with events.
(default: {None})
"""
if self.large_img is not None:
EditWindow(self, self.large_img)
class Buttons(tk.Frame):
def __init__(self, parent):
"""Class widget for the buttons at the bottom of the screen
Arguments:
parent {object} -- class that called this
"""
tk.Frame.__init__(self, parent)
self.parent = parent
arrow_left = Image.open(os.path.join(os.path.dirname(__file__), "Assets", "arrow_left.png"))
rotate_right = Image.open(os.path.join(os.path.dirname(__file__), "Assets", "rotate_right.png"))
self.img_backwards = ImageTk.PhotoImage(arrow_left)
self.img_forwards = ImageTk.PhotoImage(arrow_left.rotate(180))
self.img_rotate_anticlockwise = ImageTk.PhotoImage(ImageOps.mirror(rotate_right))
self.img_rotate_clockwise = ImageTk.PhotoImage(rotate_right)
self.img_clipboard = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "clipboard.png"))
self.img_fullscreen = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "fullscreen.png"))
self.img_save = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "save.png"))
self.img_flip = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "flip.png"))
self.img_edit = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "edit.png"))
self.lbl_text = tk.Label(self)
self.lbl_text.grid(row = 0, column = 0, columnspan = 11)
ttk.Button(self, image = self.img_backwards, command = self.backwards).grid(row = 1, column = 0)
ttk.Button(self, image = self.img_rotate_anticlockwise, command = self.anticlockwise).grid(row = 1, column = 1)
ttk.Separator(self, orient=tk.VERTICAL).grid(row = 1, column = 2, sticky = 'ns', padx = 3)
ttk.Button(self, image = self.img_edit, command = self.parent.edit_image).grid(row = 1, column = 3)
ttk.Button(self, image = self.img_clipboard, command = self.clipboard).grid(row = 1, column = 4)
ttk.Button(self, image = self.img_fullscreen, command = self.fullscreen).grid(row = 1, column = 5)
ttk.Button(self, image = self.img_save, command = self.save).grid(row = 1, column = 6)
ttk.Button(self, image = self.img_flip, command = self.flip).grid(row = 1, column = 7)
ttk.Separator(self, orient=tk.VERTICAL).grid(row = 1, column = 8, sticky = 'ns', padx = 3)
ttk.Button(self, image = self.img_rotate_clockwise, command = self.clockwise).grid(row = 1, column = 9)
ttk.Button(self, image = self.img_forwards, command = self.forwards).grid(row = 1, column = 10)
def __get_images(self):
"""Private. Returns all avaliable files
Returns:
list -- List of files that the app can open
"""
return sorted([file for file in os.listdir(os.path.split(self.parent.parent.img_viewer.path)[:-1][0]) if os.path.splitext(file)[1].lower() in IMPORT_FILES], key=str.casefold)
def backwards(self, event = None):
"""Event placeholder for when someone wants to go back an image.
Wraps around if required.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
path = self.parent.parent.img_viewer.path
if path is not None:
images = self._Buttons__get_images()
index = images.index(os.path.split(self.parent.parent.img_viewer.path)[-1:][0])
if index == 0:
self.parent.parent.img_viewer.open_image(os.path.join(os.path.split(path)[:-1][0], images[-1]))
else:
self.parent.parent.img_viewer.open_image(os.path.join(os.path.split(path)[:-1][0], images[index - 1]))
def forwards(self, event = None):
"""Event placeholder for when someone wants to go forwards an image.
Wraps around if nessisary.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
path = self.parent.parent.img_viewer.path
if path is not None:
images = self._Buttons__get_images()
index = images.index(os.path.split(self.parent.parent.img_viewer.path)[-1:][0])
try:
images.index(os.path.split(self.parent.parent.img_viewer.path)[-1:][0])
self.parent.parent.img_viewer.open_image(os.path.join(os.path.split(path)[:-1][0], images[index + 1]))
except IndexError:
self.parent.parent.img_viewer.open_image(os.path.join(os.path.split(path)[:-1][0], images[0]))
def clipboard(self, event = None):
"""Adds the path to the current image to the clipboard.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
print(self.parent.parent.img_viewer.path)
self.parent.parent.clipboard_clear()
self.parent.parent.clipboard_append(self.parent.parent.img_viewer.path)
self.parent.parent.update()
def save(self, event = None):
"""Allows the user to copy this file to another directory
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
orig = self.parent.parent.img_viewer.path
if orig is not None:
path = filedialog.askdirectory()
if path != '':
shutil.copy2(orig, path)
messagebox.showinfo('Operation complete', 'Copied file %s to %s.' % (os.path.normpath(orig), os.path.normpath(path)))
def fullscreen(self, event = None):
"""Opens a Toplevel window with the current image shown in full on it.
Calls the FullscreenWindow() class.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
FullscreenWindow(self, Image.open(self.parent.parent.img_viewer.path))
def anticlockwise(self, event = None):
"""Rotates the current image 90 degress anticlockwise.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
self.parent.open_image(self.parent.large_img.rotate(-90, expand = 1))
def clockwise(self, event = None):
"""Rotates the current image 90 degrees clockwise.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
self.parent.open_image(self.parent.large_img.rotate(90, expand = 1))
def flip(self, event = None):
"""Flips the image.
Keyword Arguments:
event {event} -- Makes this method work with events (default: {None})
"""
if self.parent.parent.img_viewer.path is not None:
self.parent.open_image(ImageOps.mirror(self.parent.large_img))
class FullscreenWindow(tk.Toplevel):
def __init__(self, parent, img):
"""Opens a tk.Toplevel window which shows the image as large as possible on
it. Closed by Esc key.
Arguments:
parent {object} -- class that called this class.
img {Image} -- image to display.
"""
tk.Toplevel.__init__(self, parent)
self.iconbitmap(os.path.join(os.path.dirname(__file__), 'Assets', 'icon.ico'))
self.attributes('-fullscreen', True)
self.focus_set()
self.update_idletasks()
width = self.winfo_height()
height = self.winfo_height()
imgwidth = img.size[0]
imgheight = img.size[1]
img = img.resize((int(imgwidth * height / imgheight) - 5, height - 5))
tkimg = ImageTk.PhotoImage(img)
lbl_img = ttk.Label(self, image=tkimg)
lbl_img.image = tkimg
lbl_img.grid(row=0, column=0, sticky='nsew')
self.bind('<Escape>', lambda a: self.destroy())
class EditWindow(tk.Toplevel):
def __init__(self, parent, img):
"""tk.Toplevel widget where the user can preform various manupulations
on an image and saves the new one to disc.
Arguments:
parent {object} -- class that called this class
img {Image} -- image to be operated on.
"""
tk.Toplevel.__init__(self, parent)
self.parent = parent
self.img = img
self.iconbitmap(os.path.join(os.path.dirname(__file__), "Assets", "icon.ico"))
self.resizable(0, 0)
self.orig_dims = img.size
lbf_resize = tk.LabelFrame(self, text = "Resize image")
lbf_resize.grid(row = 0, column = 0, columnspan = 2, padx = 5, pady = 5)
self.maintainratio = tk.BooleanVar()
ttk.Label(lbf_resize, text = "Width:").grid(row = 0, column = 0, padx = 6, pady = 6)
ttk.Label(lbf_resize, text = "Height:").grid(row = 1, column = 0, padx = 6, pady = 6)
self.ent_x = ttk.Entry(lbf_resize, width = 5)
self.ent_x.grid(row = 0, column = 1, padx = 3, pady = 6)
self.ent_y = ttk.Entry(lbf_resize, width = 5)
self.ent_y.grid(row = 1, column = 1, padx = 3, pady = 6)
self.__icon_chain = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "chain.png"))
ttk.Button(lbf_resize, image = self.__icon_chain, command = lambda: self.__fix_ratio("x")).grid(row = 0, column = 2, padx = 3, pady = 6)
ttk.Button(lbf_resize, image = self.__icon_chain, command = lambda: self.__fix_ratio("y")).grid(row = 1, column = 2, padx = 3, pady = 6)
self.ent_x.insert(0, self.orig_dims[0])
self.ent_y.insert(0, self.orig_dims[1])
lbf_transformation = tk.LabelFrame(self, text = "Image transformation")
lbf_transformation.grid(row = 1, column = 0, columnspan = 2, padx = 5, pady = 5)
self.flip = tk.BooleanVar()
ttk.Checkbutton(lbf_transformation, text = "Flip image", variable = self.flip, onvalue = True, offvalue = False).grid(row = 0, column = 0, columnspan = 2, padx = 6, pady = 6)
tk.Label(lbf_transformation, text = "Rotation:").grid(row = 1, column = 0, padx = 6, pady = 6)
self.ent_rotate = ttk.Entry(lbf_transformation, width = 5)
self.ent_rotate.grid(row = 1, column = 1, padx = 3, pady = 3)
ttk.Separator(self).grid(row = 2, column = 0, columnspan = 2, sticky = "ew")
self.__icon_tick = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "tick.png"))
self.__icon_cross = tk.PhotoImage(file = os.path.join(os.path.dirname(__file__), "Assets", "cross.png"))
ttk.Button(self, text = "Save", image = self.__icon_tick, compound = tk.LEFT, command = self.__go).grid(row = 3, column = 0, padx = 5, pady = 5, sticky = tk.W)
ttk.Button(self, text = "Cancel", image = self.__icon_cross, compound = tk.LEFT, command = lambda: self.destroy()).grid(row = 3, column = 1, padx = 5, pady = 5, sticky = tk.E)
def __fix_ratio(self, hw):
"""Private. Works out the other dimention so that the aspect ratio is mantained.
Arguments:
hw {str} -- char indicating if the calculations should be preformed on the height
or the width.
"""
try:
if hw == "x":
self.ent_y.delete(0, tk.END)
self.ent_y.insert(0, self.__calc(self.img, width = int(self.ent_x.get())))
elif hw == "y":
self.ent_x.delete(0, tk.END)
self.ent_x.insert(0, self.__calc(self.img, height = int(self.ent_y.get())))
except ValueError:
messagebox.showwarning("", "Please only input integers")
self.focus_set()
def __calc(self, img, **kwargs):
"""Private. Calculates the other dimention so that aspect ratio is mantained.
Arguments:
img {Image} -- image that's going to be resized. Needed for the calculation
Raises:
TypeError -- Thrown if neither 'height' nor 'width' args are found.
Returns:
int -- size of the other dim.
"""
if list(kwargs.keys())[0] == 'height':
baseheight = kwargs['height']
hpercent = baseheight / float(img.size[1])
wsize = int(float(img.size[0]) * float(hpercent))
return wsize
elif list(kwargs.keys())[0] == 'width':
basewidth = kwargs['width']
wpercent = basewidth / float(img.size[0])
hsize = int(float(img.size[1]) * float(wpercent))
return hsize
raise TypeError("Missing argument: must have 'height' or 'width'.")
def __go(self):
"""Private. Does transformations and saves to disc.
Returns:
None -- If user cancelled.
"""
if self.ent_x.get().isdigit() and self.ent_y.get().isdigit():
self.img = self.img.resize((int(self.ent_x.get()), int(self.ent_y.get())))
if self.flip.get():
self.img = ImageOps.mirror(self.img)
if self.ent_rotate.get() != '':
if self.ent_rotate.get().isdigit():
self.img = self.img.rotate(int(self.ent_rotate.get()), expand = 1)
else:
messagebox.showwarning("", "Please only input integers")
self.focus_set()
return
path = filedialog.asksaveasfile(filetypes = (("PNG images", "*.png"), ("JPEG images", "*.jpg")))
if path == '' or path is None:
return #user cancelled
else:
path = path.name
if os.path.splitext(path)[1] == "":
messagebox.showinfo("", "No file extension specified. Saving as .png.")
os.remove(path)
path += ".png"
self.img.save(path)
messagebox.showinfo("Done", "Image saved at %s" % path)
else:
messagebox.showwarning("", "Please only input integers")
self.focus_set()
def max_height():
"""Returns an appropriate height for the app so that it fits on the screen.
Returns:
{int} -- height of app (pixels)
"""
return int(min([i.height for i in screeninfo.get_monitors()]) * 2/3)
def max_width():
"""Returns an appropriate width for the app so that it fits on the screen.
Returns:
{int} -- the width of the app (pixels)
"""
return int(min([i.width for i in screeninfo.get_monitors()]) * 2/3)
def get_filetypes():
"""Returns tuples of the avaliable filetpyes for use in a filedialog
Returns:
tuple -- avaliable filetypes
"""
return (('%s images' % type[1:].upper(), type) for type in IMPORT_FILES)
#for testing purposes only
if __name__ == "__main__":
print("My current __file__ is '%s'" % __file__)
print("My CWD is '%s'" % os.getcwd())
print("The things in my CWD are: ", os.listdir(os.getcwd()))
try:
start = sys.argv[1]
except:
start = None
root = App(path = start)
root.mainloop()
|