-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_mainwindow.py
More file actions
1892 lines (1659 loc) · 82.2 KB
/
ui_mainwindow.py
File metadata and controls
1892 lines (1659 loc) · 82.2 KB
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main Window UI for Image Converter
"""
import os
from pathlib import Path
from PySide6.QtWidgets import (
QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
QLabel, QPushButton, QComboBox, QLineEdit, QProgressBar,
QFileDialog, QMessageBox, QScrollArea, QCheckBox, QGroupBox,
QSpinBox, QDoubleSpinBox, QDialog, QDialogButtonBox
)
from PySide6.QtCore import Qt, QThread, Signal, QMimeData
from PySide6.QtGui import QPixmap, QDragEnterEvent, QDropEvent, QFont, QClipboard, QKeySequence, QShortcut, QIcon
from PySide6.QtWidgets import QApplication
from converter import ImageConverter
from downloader import ImageDownloader
def get_app_icon():
"""Get application icon for dialogs"""
def get_resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
import sys
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
icon_names = ["icon.ico", "icon.png"]
for icon_name in icon_names:
icon_path = get_resource_path(icon_name)
if os.path.exists(icon_path):
icon = QIcon(icon_path)
if not icon.isNull():
return icon
return QIcon() # Return empty icon if none found
def center_window(window):
"""Center a window on the screen"""
try:
# Get the primary screen
screen = QApplication.primaryScreen()
if screen:
screen_geometry = screen.availableGeometry()
window_geometry = window.frameGeometry()
# Calculate center position
center_x = screen_geometry.center().x() - window_geometry.width() // 2
center_y = screen_geometry.center().y() - window_geometry.height() // 2
# Move window to center
window.move(center_x, center_y)
except Exception as e:
print(f"Failed to center window: {e}")
# Fallback: use default positioning
class PreviewDialog(QDialog):
def __init__(self, preview_data, dpi=300, quality=90, parent=None):
super().__init__(parent)
self.preview_data = preview_data # List of (image_path, size, format, output_name) tuples
self.dpi = dpi
self.quality = quality
self.setWindowTitle("Preview Before Saving")
self.setModal(True)
self.resize(800, 600)
self.setup_dialog_icon()
self.setup_ui()
# Center the dialog
center_window(self)
def setup_ui(self):
layout = QVBoxLayout()
# Title
title_label = QLabel("Preview of images to be saved:")
title_label.setStyleSheet("font-size: 14px; font-weight: bold; color: #0078d4; margin-bottom: 5px;")
layout.addWidget(title_label)
# Conversion settings summary - always show user's selected settings
if len(self.preview_data) > 0:
format_name = self.preview_data[0][2] # Get format from first item
if format_name.lower() == 'webp':
actual_quality = min(self.quality, 85)
if actual_quality != self.quality:
settings_text = f"Settings: Quality {self.quality}% → {actual_quality}% (WebP) | DPI not supported | {len(self.preview_data)} files"
else:
settings_text = f"Settings: Quality {self.quality}% (WebP) | DPI not supported | {len(self.preview_data)} files"
elif format_name.lower() == 'ico':
settings_text = f"Settings: Quality {self.quality}% (not used) | DPI not supported | {len(self.preview_data)} ICO files"
elif format_name.lower() == 'png':
settings_text = f"Settings: DPI {self.dpi} (metadata) | Quality {self.quality}% (compression) | {len(self.preview_data)} files"
else: # JPEG/JPG
settings_text = f"Settings: DPI {self.dpi} | Quality {self.quality}% | {len(self.preview_data)} files"
else:
settings_text = f"Settings: DPI {self.dpi} | Quality {self.quality}% | 0 files"
settings_label = QLabel(settings_text)
settings_label.setStyleSheet("font-size: 11px; color: #888; margin-bottom: 10px;")
layout.addWidget(settings_label)
# Scroll area for previews
scroll_area = QScrollArea()
scroll_widget = QWidget()
scroll_layout = QVBoxLayout(scroll_widget)
for i, (image_path, size, format_name, output_name, original_path) in enumerate(self.preview_data):
# Create preview item
item_frame = QGroupBox(f"Preview {i+1}")
item_layout = QHBoxLayout(item_frame)
# Image preview
preview_size = 150 # Define preview size at the top
try:
pixmap = QPixmap(image_path)
if not pixmap.isNull():
# Scale preview to reasonable size
scaled_pixmap = pixmap.scaled(preview_size, preview_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
image_label = QLabel()
image_label.setPixmap(scaled_pixmap)
image_label.setAlignment(Qt.AlignCenter)
image_label.setStyleSheet("""
QLabel {
border: 1px solid #666;
background-color: #2b2b2b;
border-radius: 5px;
padding: 5px;
}
""")
item_layout.addWidget(image_label)
else:
# Fallback if image can't be loaded
image_label = QLabel("Preview\nNot Available")
image_label.setAlignment(Qt.AlignCenter)
image_label.setMinimumSize(preview_size, preview_size)
image_label.setStyleSheet("""
QLabel {
border: 1px solid #666;
background-color: #2b2b2b;
color: #888;
border-radius: 5px;
padding: 5px;
}
""")
item_layout.addWidget(image_label)
except Exception:
# Error loading image
image_label = QLabel("Error\nLoading\nPreview")
image_label.setAlignment(Qt.AlignCenter)
image_label.setMinimumSize(preview_size, preview_size)
image_label.setStyleSheet("""
QLabel {
border: 1px solid #666;
background-color: #2b2b2b;
color: #888;
border-radius: 5px;
padding: 5px;
}
""")
item_layout.addWidget(image_label)
# Info panel
info_layout = QVBoxLayout()
# File name
name_label = QLabel(f"📄 File: {output_name}")
name_label.setStyleSheet("font-weight: bold; color: #ffffff; margin-bottom: 5px;")
info_layout.addWidget(name_label)
# Dimensions
if size == "original":
try:
from PIL import Image
# Use original image path to get true original dimensions
with Image.open(original_path) as img:
orig_width, orig_height = img.size
# Check if ICO format needs size optimization for original
if format_name.lower() == 'ico' and (orig_width > 256 or orig_height > 256):
# Show the optimized size for ICO
max_size = 256
if orig_width > orig_height:
opt_height = int(orig_height * max_size / orig_width)
opt_width = max_size
else:
opt_width = int(orig_width * max_size / orig_height)
opt_height = max_size
size_text = f"📐 Size: {orig_width} x {orig_height} → {opt_width} x {opt_height} pixels (Original)"
else:
size_text = f"📐 Size: {orig_width} x {orig_height} pixels (Original)"
except:
size_text = "📐 Size: Original"
else:
if isinstance(size, tuple):
width, height = size
# Check if ICO size was optimized
if format_name.lower() == 'ico' and (width > 256 or height > 256):
# Show the optimized size
max_size = 256
if width > height:
opt_height = int(height * max_size / width)
opt_width = max_size
else:
opt_width = int(width * max_size / height)
opt_height = max_size
size_text = f"📐 Size: {width} x {height} → {opt_width} x {opt_height} pixels"
else:
size_text = f"📐 Size: {width} x {height} pixels"
else:
size_text = f"📐 Size: {size}"
size_label = QLabel(size_text)
size_label.setStyleSheet("color: #cccccc; margin-bottom: 3px;")
info_layout.addWidget(size_label)
# Format
format_label = QLabel(f"🎨 Format: {format_name.upper()}")
format_label.setStyleSheet("color: #cccccc; margin-bottom: 3px;")
info_layout.addWidget(format_label)
# DPI information (show for all formats with appropriate notes)
if format_name.lower() in ['png', 'jpeg', 'jpg']:
if format_name.lower() == 'png':
dpi_text = f"🔍 DPI: {self.dpi} (metadata only)"
else:
dpi_text = f"🔍 DPI: {self.dpi}"
dpi_label = QLabel(dpi_text)
dpi_label.setStyleSheet("color: #cccccc; margin-bottom: 3px;")
info_layout.addWidget(dpi_label)
elif format_name.lower() == 'webp':
# WebP doesn't support DPI metadata
dpi_label = QLabel(f"🔍 DPI: {self.dpi} (not supported in WebP)")
dpi_label.setStyleSheet("color: #888; margin-bottom: 3px; font-style: italic;")
info_layout.addWidget(dpi_label)
elif format_name.lower() == 'ico':
# ICO doesn't support DPI metadata
dpi_label = QLabel(f"🔍 DPI: {self.dpi} (not supported in ICO)")
dpi_label.setStyleSheet("color: #888; margin-bottom: 3px; font-style: italic;")
info_layout.addWidget(dpi_label)
# Quality information - always show user's selected quality
if format_name.lower() in ['jpeg', 'jpg']:
quality_text = f"⚡ Quality: {self.quality}%"
quality_label = QLabel(quality_text)
quality_label.setStyleSheet("color: #cccccc; margin-bottom: 3px;")
info_layout.addWidget(quality_label)
elif format_name.lower() == 'webp':
# For WebP, show both user setting and actual used quality
actual_quality = min(self.quality, 85)
if actual_quality == self.quality:
quality_text = f"⚡ Quality: {self.quality}% (Fast compression)"
else:
quality_text = f"⚡ Quality: {self.quality}% → {actual_quality}% (WebP optimized)"
quality_label = QLabel(quality_text)
quality_label.setStyleSheet("color: #cccccc; margin-bottom: 3px;")
info_layout.addWidget(quality_label)
# Add note about WebP compression
webp_note = QLabel("📝 WebP: Modern format with superior compression")
webp_note.setStyleSheet("color: #666; font-size: 10px; margin-bottom: 3px;")
info_layout.addWidget(webp_note)
elif format_name.lower() == 'png':
# PNG: Show user's quality setting and compression level
if self.quality >= 90:
compression_info = "Low compression"
elif self.quality >= 70:
compression_info = "Medium compression"
else:
compression_info = "High compression"
quality_text = f"⚡ Quality: {self.quality}% ({compression_info})"
quality_label = QLabel(quality_text)
quality_label.setStyleSheet("color: #cccccc; margin-bottom: 3px;")
info_layout.addWidget(quality_label)
elif format_name.lower() == 'ico':
# ICO: Show user's quality setting but note it doesn't apply
quality_text = f"⚡ Quality: {self.quality}% (lossless icon format)"
quality_label = QLabel(quality_text)
quality_label.setStyleSheet("color: #888; margin-bottom: 3px; font-style: italic;")
info_layout.addWidget(quality_label)
# Add note about ICO format
if isinstance(size, tuple):
width, height = size
if width <= 48 and height <= 48:
ico_note = QLabel("📝 ICO: Optimal size for Windows icons")
elif width <= 128 and height <= 128:
ico_note = QLabel("📝 ICO: Good for high-DPI displays")
elif width <= 256 and height <= 256:
ico_note = QLabel("📝 ICO: Maximum reliable size")
elif width > 256 or height > 256:
ico_note = QLabel("📝 ICO: Size reduced to 256x256 (PIL limitation)")
else:
ico_note = QLabel("📝 ICO: Good size for compatibility")
elif size == "original":
# Check original image size for ICO format note using original path
try:
from PIL import Image
with Image.open(original_path) as img:
orig_width, orig_height = img.size
if orig_width > 256 or orig_height > 256:
ico_note = QLabel("📝 ICO: Original size reduced to 256x256 (PIL limitation)")
else:
ico_note = QLabel("📝 ICO: Original size, good compatibility")
except:
ico_note = QLabel("📝 ICO: Windows icon format, max 256x256 reliable")
else:
ico_note = QLabel("📝 ICO: Windows icon format, max 256x256 reliable")
ico_note.setStyleSheet("color: #666; font-size: 10px; margin-bottom: 3px;")
info_layout.addWidget(ico_note)
# File size estimate (if possible)
try:
import os
if os.path.exists(image_path):
file_size = os.path.getsize(image_path)
if file_size < 1024:
size_str = f"{file_size} B"
elif file_size < 1024 * 1024:
size_str = f"{file_size / 1024:.1f} KB"
else:
size_str = f"{file_size / (1024 * 1024):.1f} MB"
file_size_text = f"💾 File size: {size_str}"
if format_name.lower() == 'ico':
file_size_text += " (varies by icon size)"
file_size_label = QLabel(file_size_text)
file_size_label.setStyleSheet("color: #888; font-size: 11px;")
info_layout.addWidget(file_size_label)
except:
pass
info_layout.addStretch()
item_layout.addLayout(info_layout)
scroll_layout.addWidget(item_frame)
scroll_area.setWidget(scroll_widget)
scroll_area.setWidgetResizable(True)
scroll_area.setMinimumHeight(400)
layout.addWidget(scroll_area)
# Summary
summary_label = QLabel(f"Total files to be saved: {len(self.preview_data)}")
summary_label.setStyleSheet("font-weight: bold; color: #0078d4; margin-top: 10px;")
layout.addWidget(summary_label)
# Buttons
button_layout = QHBoxLayout()
cancel_btn = QPushButton("❌ Cancel")
cancel_btn.clicked.connect(self.reject)
cancel_btn.setStyleSheet("""
QPushButton {
background-color: #666;
color: white;
border: none;
border-radius: 5px;
padding: 8px 16px;
font-size: 12px;
}
QPushButton:hover {
background-color: #777;
}
""")
button_layout.addWidget(cancel_btn)
button_layout.addStretch()
save_btn = QPushButton("💾 Save All Images")
save_btn.clicked.connect(self.accept)
save_btn.setStyleSheet("""
QPushButton {
background-color: #0078d4;
color: white;
border: none;
border-radius: 5px;
padding: 8px 16px;
font-size: 12px;
font-weight: bold;
}
QPushButton:hover {
background-color: #106ebe;
}
""")
button_layout.addWidget(save_btn)
layout.addLayout(button_layout)
self.setLayout(layout)
def closeEvent(self, event):
"""Clean up temporary preview files when dialog is closed"""
self.cleanup_temp_files()
super().closeEvent(event)
def reject(self):
"""Clean up temporary files when dialog is cancelled"""
self.cleanup_temp_files()
super().reject()
def accept(self):
"""Clean up temporary files when dialog is accepted"""
self.cleanup_temp_files()
super().accept()
def cleanup_temp_files(self):
"""Remove temporary preview files"""
import os
for temp_path, _, _, _, _ in self.preview_data:
try:
if os.path.exists(temp_path):
os.remove(temp_path)
except Exception:
pass # Ignore cleanup errors
def setup_dialog_icon(self):
"""Setup dialog icon to match main window"""
def get_resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
import sys
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
icon_names = ["icon.ico", "icon.png"]
for icon_name in icon_names:
icon_path = get_resource_path(icon_name)
if os.path.exists(icon_path):
icon = QIcon(icon_path)
if not icon.isNull():
self.setWindowIcon(icon)
break
class CustomSizeDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Custom Size")
self.setModal(True)
self.resize(350, 200)
self.setup_dialog_icon()
layout = QVBoxLayout()
# Unit selection
unit_layout = QHBoxLayout()
unit_layout.addWidget(QLabel("Unit:"))
self.unit_combo = QComboBox()
self.unit_combo.addItems(["Pixels", "Centimeters", "Inches"])
self.unit_combo.setCurrentText("Pixels")
self.unit_combo.currentTextChanged.connect(self.on_unit_changed)
unit_layout.addWidget(self.unit_combo)
layout.addLayout(unit_layout)
# Size inputs with lock - horizontal layout for cleaner design
size_container = QHBoxLayout()
# Left side - Width and Height inputs
inputs_layout = QVBoxLayout()
# Width input
width_layout = QHBoxLayout()
width_layout.addWidget(QLabel("Width:"))
self.width_spin = QDoubleSpinBox()
self.width_spin.setRange(0.1, 10000)
self.width_spin.setValue(512)
self.width_spin.setDecimals(1)
self.width_spin.valueChanged.connect(self.on_width_changed)
width_layout.addWidget(self.width_spin)
self.width_unit_label = QLabel("px")
width_layout.addWidget(self.width_unit_label)
inputs_layout.addLayout(width_layout)
# Height input
height_layout = QHBoxLayout()
height_layout.addWidget(QLabel("Height:"))
self.height_spin = QDoubleSpinBox()
self.height_spin.setRange(0.1, 10000)
self.height_spin.setValue(512)
self.height_spin.setDecimals(1)
self.height_spin.valueChanged.connect(self.on_height_changed)
height_layout.addWidget(self.height_spin)
self.height_unit_label = QLabel("px")
height_layout.addWidget(self.height_unit_label)
inputs_layout.addLayout(height_layout)
size_container.addLayout(inputs_layout)
# Right side - Lock button (positioned to the right)
lock_container = QVBoxLayout()
lock_container.addStretch() # Push button to center vertically
self.lock_button = QPushButton("🔒")
self.lock_button.setCheckable(True)
self.lock_button.setChecked(True) # Locked by default
self.lock_button.setMaximumSize(40, 40)
self.lock_button.setMinimumSize(40, 40)
self.lock_button.setToolTip("Lock aspect ratio (maintain proportions)")
self.lock_button.setStyleSheet("""
QPushButton {
background-color: #0078d4;
color: white;
border: none;
border-radius: 15px;
font-size: 14px;
font-weight: bold;
margin-left: 10px;
}
QPushButton:hover {
background-color: #106ebe;
}
QPushButton:checked {
background-color: #0078d4;
}
QPushButton:!checked {
background-color: #666;
}
""")
self.lock_button.clicked.connect(self.toggle_aspect_lock)
lock_container.addWidget(self.lock_button)
lock_container.addStretch() # Push button to center vertically
size_container.addLayout(lock_container)
layout.addLayout(size_container)
# DPI input (for cm/inch conversions)
dpi_layout = QHBoxLayout()
dpi_layout.addWidget(QLabel("DPI:"))
self.dpi_spin = QSpinBox()
self.dpi_spin.setRange(72, 600)
self.dpi_spin.setValue(300)
self.dpi_spin.valueChanged.connect(self.update_pixel_preview)
dpi_layout.addWidget(self.dpi_spin)
self.dpi_label = QLabel("(for cm/inch conversion)")
self.dpi_label.setStyleSheet("color: #888; font-size: 10px;")
dpi_layout.addWidget(self.dpi_label)
layout.addLayout(dpi_layout)
# Preview label
self.preview_label = QLabel("Size in pixels: 512 x 512")
self.preview_label.setStyleSheet("color: #0078d4; font-weight: bold; padding: 5px;")
layout.addWidget(self.preview_label)
# Buttons
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
self.setLayout(layout)
# Initialize aspect ratio tracking
self.aspect_ratio = 1.0 # 512/512 = 1.0
self.updating_from_lock = False # Prevent recursive updates
# Initialize unit display
self.on_unit_changed("Pixels")
# Center the dialog
center_window(self)
def toggle_aspect_lock(self):
"""Toggle the aspect ratio lock and update button appearance"""
is_locked = self.lock_button.isChecked()
if is_locked:
self.lock_button.setText("🔒")
self.lock_button.setToolTip("Lock aspect ratio (maintain proportions)")
# Update aspect ratio based on current values
width = self.width_spin.value()
height = self.height_spin.value()
if height > 0:
self.aspect_ratio = width / height
else:
self.lock_button.setText("🔓")
self.lock_button.setToolTip("Unlock aspect ratio (independent width/height)")
def on_width_changed(self):
"""Handle width change and update height if locked"""
if self.lock_button.isChecked() and not self.updating_from_lock:
self.updating_from_lock = True
width = self.width_spin.value()
new_height = width / self.aspect_ratio if self.aspect_ratio > 0 else width
self.height_spin.setValue(new_height)
self.updating_from_lock = False
self.update_pixel_preview()
def on_height_changed(self):
"""Handle height change and update width if locked"""
if self.lock_button.isChecked() and not self.updating_from_lock:
self.updating_from_lock = True
height = self.height_spin.value()
new_width = height * self.aspect_ratio
self.width_spin.setValue(new_width)
self.updating_from_lock = False
self.update_pixel_preview()
def on_unit_changed(self, unit):
"""Handle unit change and update UI accordingly"""
# Store current pixel values for conversion
current_width_px = self.get_current_width_pixels()
current_height_px = self.get_current_height_pixels()
if unit == "Pixels":
self.width_unit_label.setText("px")
self.height_unit_label.setText("px")
self.dpi_spin.setEnabled(False)
self.dpi_label.setVisible(False)
self.width_spin.setRange(1, 10000)
self.height_spin.setRange(1, 10000)
self.width_spin.setDecimals(0)
self.height_spin.setDecimals(0)
self.width_spin.setSuffix("")
self.height_spin.setSuffix("")
self.width_spin.setValue(current_width_px)
self.height_spin.setValue(current_height_px)
elif unit == "Centimeters":
self.width_unit_label.setText("cm")
self.height_unit_label.setText("cm")
self.dpi_spin.setEnabled(True)
self.dpi_label.setVisible(True)
self.width_spin.setRange(0.1, 100)
self.height_spin.setRange(0.1, 100)
self.width_spin.setDecimals(1)
self.height_spin.setDecimals(1)
self.width_spin.setSuffix(" cm")
self.height_spin.setSuffix(" cm")
# Convert pixels to cm
dpi = self.dpi_spin.value()
width_cm = round(current_width_px / dpi * 2.54, 1)
height_cm = round(current_height_px / dpi * 2.54, 1)
self.width_spin.setValue(width_cm)
self.height_spin.setValue(height_cm)
elif unit == "Inches":
self.width_unit_label.setText("in")
self.height_unit_label.setText("in")
self.dpi_spin.setEnabled(True)
self.dpi_label.setVisible(True)
self.width_spin.setRange(0.1, 40)
self.height_spin.setRange(0.1, 40)
self.width_spin.setDecimals(2)
self.height_spin.setDecimals(2)
self.width_spin.setSuffix(" in")
self.height_spin.setSuffix(" in")
# Convert pixels to inches
dpi = self.dpi_spin.value()
width_in = round(current_width_px / dpi, 2)
height_in = round(current_height_px / dpi, 2)
self.width_spin.setValue(width_in)
self.height_spin.setValue(height_in)
# Update aspect ratio after unit conversion
if self.lock_button.isChecked():
width = self.width_spin.value()
height = self.height_spin.value()
if height > 0:
self.aspect_ratio = width / height
self.update_pixel_preview()
def get_current_width_pixels(self):
"""Get current width in pixels regardless of unit"""
unit = self.unit_combo.currentText()
width_val = self.width_spin.value()
if unit == "Pixels":
return int(width_val)
elif unit == "Centimeters":
dpi = self.dpi_spin.value()
return int(width_val * dpi / 2.54)
elif unit == "Inches":
dpi = self.dpi_spin.value()
return int(width_val * dpi)
return 512 # fallback
def get_current_height_pixels(self):
"""Get current height in pixels regardless of unit"""
unit = self.unit_combo.currentText()
height_val = self.height_spin.value()
if unit == "Pixels":
return int(height_val)
elif unit == "Centimeters":
dpi = self.dpi_spin.value()
return int(height_val * dpi / 2.54)
elif unit == "Inches":
dpi = self.dpi_spin.value()
return int(height_val * dpi)
return 512 # fallback
def update_pixel_preview(self):
"""Update the pixel preview based on current unit and values"""
unit = self.unit_combo.currentText()
width_val = self.width_spin.value()
height_val = self.height_spin.value()
if unit == "Pixels":
width_px = width_val
height_px = height_val
elif unit == "Centimeters":
dpi = self.dpi_spin.value()
width_px = int(width_val * dpi / 2.54)
height_px = int(height_val * dpi / 2.54)
elif unit == "Inches":
dpi = self.dpi_spin.value()
width_px = int(width_val * dpi)
height_px = int(height_val * dpi)
self.preview_label.setText(f"Size in pixels: {width_px} x {height_px}")
def get_size(self):
"""Return size in pixels regardless of input unit"""
unit = self.unit_combo.currentText()
width_val = self.width_spin.value()
height_val = self.height_spin.value()
if unit == "Pixels":
return (width_val, height_val)
elif unit == "Centimeters":
dpi = self.dpi_spin.value()
width_px = int(width_val * dpi / 2.54)
height_px = int(height_val * dpi / 2.54)
return (width_px, height_px)
elif unit == "Inches":
dpi = self.dpi_spin.value()
width_px = int(width_val * dpi)
height_px = int(height_val * dpi)
return (width_px, height_px)
def setup_dialog_icon(self):
"""Setup dialog icon to match main window"""
def get_resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
import sys
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
icon_names = ["icon.ico", "icon.png"]
for icon_name in icon_names:
icon_path = get_resource_path(icon_name)
if os.path.exists(icon_path):
icon = QIcon(icon_path)
if not icon.isNull():
self.setWindowIcon(icon)
break
class DropArea(QLabel):
file_dropped = Signal(str)
click_to_browse = Signal()
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.setAlignment(Qt.AlignCenter)
self.setText("Drag & Drop Image Here\nor\nClick to Select File\nor\nPress Ctrl+V to Paste")
self.setCursor(Qt.PointingHandCursor) # Show pointer cursor
self.setStyleSheet("""
QLabel {
border: 2px dashed #666;
border-radius: 10px;
background-color: #2b2b2b;
color: #cccccc;
font-size: 14px;
padding: 40px;
min-height: 150px;
}
QLabel:hover {
border-color: #0078d4;
background-color: #3a3a3a;
color: #ffffff;
}
""")
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
url = urls[0]
# Check if it's a local file
if url.isLocalFile():
file_path = url.toLocalFile()
if self.is_image_file(file_path):
event.acceptProposedAction()
self.setStyleSheet(self.styleSheet().replace("#2b2b2b", "#3a3a3a"))
# Check if it's a web URL with image extension
elif url.scheme() in ['http', 'https']:
url_string = url.toString()
if self.is_image_url(url_string):
event.acceptProposedAction()
self.setStyleSheet(self.styleSheet().replace("#2b2b2b", "#3a3a3a"))
# Also check for image data directly
elif event.mimeData().hasImage():
event.acceptProposedAction()
self.setStyleSheet(self.styleSheet().replace("#2b2b2b", "#3a3a3a"))
def dragLeaveEvent(self, event):
self.setStyleSheet(self.styleSheet().replace("#3a3a3a", "#2b2b2b"))
def dropEvent(self, event: QDropEvent):
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
url = urls[0]
# Handle local files
if url.isLocalFile():
file_path = url.toLocalFile()
if self.is_image_file(file_path):
self.file_dropped.emit(file_path)
event.acceptProposedAction()
# Handle web URLs
elif url.scheme() in ['http', 'https']:
url_string = url.toString()
if self.is_image_url(url_string):
# Emit the URL for download
self.file_dropped.emit(url_string)
event.acceptProposedAction()
# Handle direct image data
elif event.mimeData().hasImage():
# Save the image data to a temporary file
image = event.mimeData().imageData()
if image:
import tempfile
import uuid
temp_file = tempfile.gettempdir() + f"/dropped_image_{uuid.uuid4().hex[:8]}.png"
if image.save(temp_file):
self.file_dropped.emit(temp_file)
event.acceptProposedAction()
self.setStyleSheet(self.styleSheet().replace("#3a3a3a", "#2b2b2b"))
def mousePressEvent(self, event):
"""Handle mouse click to open file browser"""
if event.button() == Qt.LeftButton:
self.click_to_browse.emit()
super().mousePressEvent(event)
def is_image_file(self, file_path):
valid_extensions = {'.png', '.jpg', '.jpeg', '.bmp', '.webp', '.gif', '.ico', '.tiff', '.heic'}
return Path(file_path).suffix.lower() in valid_extensions
def is_image_url(self, url_string):
"""Check if URL points to an image file"""
valid_extensions = {'.png', '.jpg', '.jpeg', '.bmp', '.webp', '.gif', '.ico', '.tiff', '.heic'}
# Remove query parameters and fragments
url_path = url_string.split('?')[0].split('#')[0]
return any(url_path.lower().endswith(ext) for ext in valid_extensions)
class ImageConverterWindow(QMainWindow):
def __init__(self):
super().__init__()
self.current_image_path = None
self.save_location = str(Path.home() / "Downloads")
self.custom_size = (512, 512)
self.setWindowTitle("Image Converter")
self.resize(800, 700) # Set size first
self.setup_window_icon()
self.setup_ui()
self.setup_connections()
self.setup_clipboard()
# Center the window after everything is set up
center_window(self)
def resizeEvent(self, event):
"""Handle window resize to update image preview"""
super().resizeEvent(event)
# Reload image if one is currently loaded to fit new size
if hasattr(self, 'current_image_path') and self.current_image_path:
self.load_image(self.current_image_path)
def setup_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setSpacing(20)
main_layout.setContentsMargins(20, 20, 20, 20)
# Input Section
input_group = QGroupBox("Image Input")
input_layout = QVBoxLayout(input_group)
# Drop area (now clickable)
self.drop_area = DropArea()
input_layout.addWidget(self.drop_area)
# URL input
url_layout = QHBoxLayout()
url_layout.addWidget(QLabel("Image URL:"))
self.url_input = QLineEdit()
self.url_input.setPlaceholderText("https://example.com/image.jpg")
url_layout.addWidget(self.url_input)
self.fetch_btn = QPushButton("🌐 Fetch")
url_layout.addWidget(self.fetch_btn)
input_layout.addLayout(url_layout)
main_layout.addWidget(input_group)
# Main content area - Two column layout
content_layout = QHBoxLayout()
# Left column - Preview Section
left_column = QVBoxLayout()
preview_group = QGroupBox("Image Preview")
preview_layout = QVBoxLayout(preview_group)
# Direct label without scroll area for responsive display
self.preview_label = QLabel("No image selected")
self.preview_label.setAlignment(Qt.AlignCenter)
self.preview_label.setMinimumSize(400, 300)
self.preview_label.setScaledContents(False) # Maintain aspect ratio
self.preview_label.setStyleSheet("""
QLabel {
border: 1px solid #555;
background-color: #2b2b2b;
color: #ffffff;
border-radius: 5px;
padding: 10px;
}
""")
preview_layout.addWidget(self.preview_label)
left_column.addWidget(preview_group)
content_layout.addLayout(left_column, 1) # Give left column more space
# Right column - Options Section
right_column = QVBoxLayout()
# Format selection
format_group = QGroupBox("Output Format")
format_layout = QVBoxLayout(format_group)
self.format_combo = QComboBox()
self.format_combo.addItems(["PNG", "JPEG", "JPG", "WebP", "ICO"])
self.format_combo.setMinimumHeight(35)
format_layout.addWidget(self.format_combo)
# Resize mode controls
resize_mode_layout = QHBoxLayout()
# Lock aspect ratio checkbox (now controls resize mode dropdown)
self.lock_aspect_ratio = QCheckBox("🔒 Lock Aspect Ratio")
self.lock_aspect_ratio.setChecked(False) # Default to unchecked (stretch mode)
resize_mode_layout.addWidget(self.lock_aspect_ratio)
# Resize mode dropdown
self.resize_mode_combo = QComboBox()
self.resize_mode_combo.addItems(["Stretch", "Crop", "Fit"])
self.resize_mode_combo.setCurrentText("Stretch") # Default mode
self.resize_mode_combo.setEnabled(False) # Disabled when aspect ratio is unlocked
self.resize_mode_combo.setMinimumHeight(25)
self.resize_mode_combo.setStyleSheet("""
QComboBox {
background-color: #2b2b2b;
color: #cccccc;
border: 1px solid #666;
border-radius: 3px;
padding: 3px;
font-size: 11px;
}
QComboBox:disabled {
background-color: #1a1a1a;
color: #666;
}
QComboBox::drop-down {
border: none;
}
QComboBox::down-arrow {
width: 12px;
height: 12px;
}
""")
# Set tooltips
self.resize_mode_combo.setItemData(0, "Image will stretch to match the new size", Qt.ToolTipRole)
self.resize_mode_combo.setItemData(1, "Image will match the new size and leftovers will be cropped", Qt.ToolTipRole)
self.resize_mode_combo.setItemData(2, "Image will fit completely inside the new size and the rest will be painted with background color", Qt.ToolTipRole)
resize_mode_layout.addWidget(self.resize_mode_combo)
format_layout.addLayout(resize_mode_layout)
# DPI (Resolution) input
dpi_layout = QHBoxLayout()
dpi_label = QLabel("Resolution (DPI):")
dpi_label.setStyleSheet("color: #cccccc; font-size: 12px;")
dpi_layout.addWidget(dpi_label)