-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphoto_reducer.py
More file actions
799 lines (669 loc) · 30.2 KB
/
Copy pathphoto_reducer.py
File metadata and controls
799 lines (669 loc) · 30.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
#!/usr/bin/env python3
"""
Photo Size Reducer - A PyQt6 application for reducing image file sizes.
Supports compression, dimension resizing, batch processing, and drag & drop.
Author: Enes Ozturk
GitHub: https://github.com/nsozturk
Repository: https://github.com/nsozturk/photo-size-reducer
License: MIT
"""
import sys
import os
from pathlib import Path
from typing import Optional
from PIL import Image
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QSlider, QComboBox, QSpinBox, QCheckBox,
QFileDialog, QListWidget, QListWidgetItem, QProgressBar,
QGroupBox, QRadioButton, QButtonGroup, QSplitter, QMessageBox,
QLineEdit, QFrame, QScrollArea
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize
from PyQt6.QtGui import QPixmap, QDragEnterEvent, QDropEvent, QImage
class ImageProcessor(QThread):
"""Background thread for processing images."""
progress = pyqtSignal(int, str) # progress percentage, current file
finished_file = pyqtSignal(str, int, int) # filename, original_size, new_size
completed = pyqtSignal(int, int) # total_original, total_saved
error = pyqtSignal(str, str) # filename, error message
def __init__(self, files: list, settings: dict):
super().__init__()
self.files = files
self.settings = settings
self._is_cancelled = False
def cancel(self):
self._is_cancelled = True
def run(self):
total_original = 0
total_new = 0
for i, file_path in enumerate(self.files):
if self._is_cancelled:
break
try:
self.progress.emit(int((i / len(self.files)) * 100), os.path.basename(file_path))
original_size = os.path.getsize(file_path)
total_original += original_size
# Process the image
new_size = self.process_image(file_path)
total_new += new_size
self.finished_file.emit(os.path.basename(file_path), original_size, new_size)
except Exception as e:
self.error.emit(os.path.basename(file_path), str(e))
self.progress.emit(100, "Complete")
self.completed.emit(total_original, total_original - total_new)
def process_image(self, file_path: str) -> int:
"""Process a single image and return the new file size."""
img = Image.open(file_path)
# Convert RGBA to RGB if saving as JPEG
output_format = self.settings['format']
if output_format == 'JPEG' and img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
# Resize if enabled
if self.settings['resize_enabled']:
if self.settings['resize_mode'] == 'percentage':
percentage = self.settings['resize_percentage'] / 100
new_width = int(img.width * percentage)
new_height = int(img.height * percentage)
elif self.settings['resize_mode'] == 'max_dimension':
max_dim = self.settings['max_dimension']
ratio = min(max_dim / img.width, max_dim / img.height)
if ratio < 1: # Only downscale
new_width = int(img.width * ratio)
new_height = int(img.height * ratio)
else:
new_width, new_height = img.width, img.height
else: # custom
new_width = self.settings['custom_width']
new_height = self.settings['custom_height']
if self.settings['maintain_aspect']:
ratio = min(new_width / img.width, new_height / img.height)
new_width = int(img.width * ratio)
new_height = int(img.height * ratio)
if (new_width, new_height) != (img.width, img.height):
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Build output path
output_dir = self.settings['output_dir']
base_name = Path(file_path).stem
suffix = self.settings['suffix']
extension = {'JPEG': '.jpg', 'PNG': '.png', 'WEBP': '.webp'}[output_format]
output_path = os.path.join(output_dir, f"{base_name}{suffix}{extension}")
# Handle duplicate filenames
counter = 1
while os.path.exists(output_path) and output_path != file_path:
output_path = os.path.join(output_dir, f"{base_name}{suffix}_{counter}{extension}")
counter += 1
# Save with compression settings
save_kwargs = {}
if output_format == 'JPEG':
save_kwargs['quality'] = self.settings['quality']
save_kwargs['optimize'] = True
elif output_format == 'PNG':
save_kwargs['optimize'] = True
if self.settings['quality'] < 100:
# PNG compression level (0-9)
save_kwargs['compress_level'] = 9 - int(self.settings['quality'] / 11)
elif output_format == 'WEBP':
save_kwargs['quality'] = self.settings['quality']
save_kwargs['method'] = 6 # Best compression
img.save(output_path, output_format, **save_kwargs)
img.close()
return os.path.getsize(output_path)
class DropZone(QFrame):
"""A widget that accepts drag and drop of image files."""
files_dropped = pyqtSignal(list)
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.setMinimumHeight(100)
self.setStyleSheet("""
DropZone {
border: 2px dashed #aaa;
border-radius: 10px;
background-color: #f5f5f5;
}
DropZone:hover {
border-color: #666;
background-color: #e8e8e8;
}
""")
layout = QVBoxLayout(self)
self.label = QLabel("Drag & Drop Images Here\nor click Browse")
self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.label.setStyleSheet("color: #666; font-size: 14px;")
layout.addWidget(self.label)
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
event.acceptProposedAction()
self.setStyleSheet("""
DropZone {
border: 2px dashed #4CAF50;
border-radius: 10px;
background-color: #e8f5e9;
}
""")
def dragLeaveEvent(self, event):
self.setStyleSheet("""
DropZone {
border: 2px dashed #aaa;
border-radius: 10px;
background-color: #f5f5f5;
}
""")
def dropEvent(self, event: QDropEvent):
self.setStyleSheet("""
DropZone {
border: 2px dashed #aaa;
border-radius: 10px;
background-color: #f5f5f5;
}
""")
files = []
valid_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff'}
for url in event.mimeData().urls():
file_path = url.toLocalFile()
if os.path.isfile(file_path):
ext = Path(file_path).suffix.lower()
if ext in valid_extensions:
files.append(file_path)
elif os.path.isdir(file_path):
# Add all images from directory
for f in os.listdir(file_path):
ext = Path(f).suffix.lower()
if ext in valid_extensions:
files.append(os.path.join(file_path, f))
if files:
self.files_dropped.emit(files)
class PreviewWidget(QWidget):
"""Widget for showing before/after preview of images."""
def __init__(self):
super().__init__()
layout = QHBoxLayout(self)
layout.setSpacing(10)
# Before preview
before_group = QGroupBox("Original")
before_layout = QVBoxLayout(before_group)
self.before_label = QLabel("No image selected")
self.before_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.before_label.setMinimumSize(200, 200)
self.before_label.setStyleSheet("background-color: #f0f0f0; border-radius: 5px;")
self.before_info = QLabel("")
self.before_info.setAlignment(Qt.AlignmentFlag.AlignCenter)
before_layout.addWidget(self.before_label)
before_layout.addWidget(self.before_info)
# After preview
after_group = QGroupBox("Preview (Estimated)")
after_layout = QVBoxLayout(after_group)
self.after_label = QLabel("No preview")
self.after_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.after_label.setMinimumSize(200, 200)
self.after_label.setStyleSheet("background-color: #f0f0f0; border-radius: 5px;")
self.after_info = QLabel("")
self.after_info.setAlignment(Qt.AlignmentFlag.AlignCenter)
after_layout.addWidget(self.after_label)
after_layout.addWidget(self.after_info)
layout.addWidget(before_group)
layout.addWidget(after_group)
def load_preview(self, file_path: str, settings: dict):
"""Load and display preview for the given image."""
try:
# Load original
pixmap = QPixmap(file_path)
if pixmap.isNull():
return
# Display original
scaled = pixmap.scaled(200, 200, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
self.before_label.setPixmap(scaled)
# Get original info
original_size = os.path.getsize(file_path)
img = Image.open(file_path)
self.before_info.setText(f"{img.width} x {img.height}\n{self.format_size(original_size)}")
# Calculate preview dimensions
preview_width, preview_height = img.width, img.height
if settings['resize_enabled']:
if settings['resize_mode'] == 'percentage':
percentage = settings['resize_percentage'] / 100
preview_width = int(img.width * percentage)
preview_height = int(img.height * percentage)
elif settings['resize_mode'] == 'max_dimension':
max_dim = settings['max_dimension']
ratio = min(max_dim / img.width, max_dim / img.height)
if ratio < 1:
preview_width = int(img.width * ratio)
preview_height = int(img.height * ratio)
else:
preview_width = settings['custom_width']
preview_height = settings['custom_height']
if settings['maintain_aspect']:
ratio = min(preview_width / img.width, preview_height / img.height)
preview_width = int(img.width * ratio)
preview_height = int(img.height * ratio)
img.close()
# Show resized preview
if preview_width != pixmap.width() or preview_height != pixmap.height():
preview_pixmap = pixmap.scaled(preview_width, preview_height,
Qt.AspectRatioMode.IgnoreAspectRatio,
Qt.TransformationMode.SmoothTransformation)
else:
preview_pixmap = pixmap
display_preview = preview_pixmap.scaled(200, 200,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
self.after_label.setPixmap(display_preview)
# Estimate new size (rough approximation)
quality = settings['quality']
size_factor = quality / 100
dimension_factor = (preview_width * preview_height) / (pixmap.width() * pixmap.height())
estimated_size = int(original_size * size_factor * dimension_factor * 0.8)
self.after_info.setText(f"{preview_width} x {preview_height}\n~{self.format_size(estimated_size)}")
except Exception as e:
self.before_info.setText(f"Error: {str(e)}")
def clear_preview(self):
"""Clear the preview displays."""
self.before_label.clear()
self.before_label.setText("No image selected")
self.before_info.setText("")
self.after_label.clear()
self.after_label.setText("No preview")
self.after_info.setText("")
@staticmethod
def format_size(size_bytes: int) -> str:
"""Format file size in human-readable format."""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.1f} TB"
class PhotoReducerApp(QMainWindow):
"""Main application window."""
def __init__(self):
super().__init__()
self.setWindowTitle("Photo Size Reducer")
self.setMinimumSize(900, 700)
self.files: list[str] = []
self.processor: Optional[ImageProcessor] = None
self.setup_ui()
self.connect_signals()
def setup_ui(self):
"""Set up the user interface."""
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# Left panel - File list and drop zone
left_panel = QWidget()
left_layout = QVBoxLayout(left_panel)
# Drop zone
self.drop_zone = DropZone()
left_layout.addWidget(self.drop_zone)
# Browse button
browse_btn = QPushButton("Browse Files...")
browse_btn.clicked.connect(self.browse_files)
left_layout.addWidget(browse_btn)
# File list
file_list_label = QLabel("Files to Process:")
left_layout.addWidget(file_list_label)
self.file_list = QListWidget()
self.file_list.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
left_layout.addWidget(self.file_list)
# File list buttons
file_btn_layout = QHBoxLayout()
remove_btn = QPushButton("Remove Selected")
remove_btn.clicked.connect(self.remove_selected)
clear_btn = QPushButton("Clear All")
clear_btn.clicked.connect(self.clear_files)
file_btn_layout.addWidget(remove_btn)
file_btn_layout.addWidget(clear_btn)
left_layout.addLayout(file_btn_layout)
# Right panel - Settings and preview
right_panel = QWidget()
right_layout = QVBoxLayout(right_panel)
# Preview
self.preview = PreviewWidget()
right_layout.addWidget(self.preview)
# Settings in scroll area
settings_scroll = QScrollArea()
settings_scroll.setWidgetResizable(True)
settings_scroll.setFrameShape(QFrame.Shape.NoFrame)
settings_widget = QWidget()
settings_layout = QVBoxLayout(settings_widget)
# Compression settings
compression_group = QGroupBox("Compression Quality")
compression_layout = QVBoxLayout(compression_group)
quality_layout = QHBoxLayout()
quality_layout.addWidget(QLabel("Quality:"))
self.quality_slider = QSlider(Qt.Orientation.Horizontal)
self.quality_slider.setRange(1, 100)
self.quality_slider.setValue(85)
self.quality_label = QLabel("85%")
self.quality_slider.valueChanged.connect(lambda v: self.quality_label.setText(f"{v}%"))
self.quality_slider.valueChanged.connect(self.update_preview)
quality_layout.addWidget(self.quality_slider)
quality_layout.addWidget(self.quality_label)
compression_layout.addLayout(quality_layout)
settings_layout.addWidget(compression_group)
# Resize settings
resize_group = QGroupBox("Resize Options")
resize_layout = QVBoxLayout(resize_group)
self.resize_checkbox = QCheckBox("Enable Resizing")
self.resize_checkbox.stateChanged.connect(self.toggle_resize_options)
self.resize_checkbox.stateChanged.connect(self.update_preview)
resize_layout.addWidget(self.resize_checkbox)
# Resize mode selection
self.resize_mode_group = QButtonGroup(self)
# Percentage resize
self.percentage_radio = QRadioButton("Resize by percentage")
self.percentage_radio.setChecked(True)
self.resize_mode_group.addButton(self.percentage_radio)
resize_layout.addWidget(self.percentage_radio)
percentage_layout = QHBoxLayout()
percentage_layout.addSpacing(20)
self.percentage_combo = QComboBox()
self.percentage_combo.addItems(["25%", "50%", "75%", "Custom"])
self.percentage_spin = QSpinBox()
self.percentage_spin.setRange(1, 100)
self.percentage_spin.setValue(50)
self.percentage_spin.setSuffix("%")
self.percentage_spin.setEnabled(False)
self.percentage_combo.currentTextChanged.connect(self.on_percentage_changed)
self.percentage_combo.currentTextChanged.connect(self.update_preview)
self.percentage_spin.valueChanged.connect(self.update_preview)
percentage_layout.addWidget(self.percentage_combo)
percentage_layout.addWidget(self.percentage_spin)
percentage_layout.addStretch()
resize_layout.addLayout(percentage_layout)
# Max dimension resize
self.max_dim_radio = QRadioButton("Max dimension (maintain aspect ratio)")
self.resize_mode_group.addButton(self.max_dim_radio)
resize_layout.addWidget(self.max_dim_radio)
max_dim_layout = QHBoxLayout()
max_dim_layout.addSpacing(20)
self.max_dim_spin = QSpinBox()
self.max_dim_spin.setRange(100, 10000)
self.max_dim_spin.setValue(1920)
self.max_dim_spin.setSuffix(" px")
self.max_dim_spin.valueChanged.connect(self.update_preview)
max_dim_layout.addWidget(self.max_dim_spin)
max_dim_layout.addStretch()
resize_layout.addLayout(max_dim_layout)
# Custom dimensions
self.custom_radio = QRadioButton("Custom dimensions")
self.resize_mode_group.addButton(self.custom_radio)
resize_layout.addWidget(self.custom_radio)
custom_layout = QHBoxLayout()
custom_layout.addSpacing(20)
self.width_spin = QSpinBox()
self.width_spin.setRange(1, 10000)
self.width_spin.setValue(1920)
self.height_spin = QSpinBox()
self.height_spin.setRange(1, 10000)
self.height_spin.setValue(1080)
self.maintain_aspect = QCheckBox("Maintain aspect ratio")
self.maintain_aspect.setChecked(True)
self.width_spin.valueChanged.connect(self.update_preview)
self.height_spin.valueChanged.connect(self.update_preview)
custom_layout.addWidget(QLabel("W:"))
custom_layout.addWidget(self.width_spin)
custom_layout.addWidget(QLabel("H:"))
custom_layout.addWidget(self.height_spin)
custom_layout.addWidget(self.maintain_aspect)
custom_layout.addStretch()
resize_layout.addLayout(custom_layout)
# Connect radio buttons to update preview
self.percentage_radio.toggled.connect(self.update_preview)
self.max_dim_radio.toggled.connect(self.update_preview)
self.custom_radio.toggled.connect(self.update_preview)
settings_layout.addWidget(resize_group)
# Initially disable resize options
self.toggle_resize_options(False)
# Output settings
output_group = QGroupBox("Output Settings")
output_layout = QVBoxLayout(output_group)
format_layout = QHBoxLayout()
format_layout.addWidget(QLabel("Format:"))
self.format_combo = QComboBox()
self.format_combo.addItems(["JPEG", "PNG", "WEBP"])
format_layout.addWidget(self.format_combo)
format_layout.addStretch()
output_layout.addLayout(format_layout)
suffix_layout = QHBoxLayout()
suffix_layout.addWidget(QLabel("Filename suffix:"))
self.suffix_input = QLineEdit("_reduced")
self.suffix_input.setMaximumWidth(150)
suffix_layout.addWidget(self.suffix_input)
suffix_layout.addStretch()
output_layout.addLayout(suffix_layout)
output_dir_layout = QHBoxLayout()
output_dir_layout.addWidget(QLabel("Output folder:"))
self.output_dir_input = QLineEdit()
self.output_dir_input.setPlaceholderText("Same as source")
self.output_dir_btn = QPushButton("Browse...")
self.output_dir_btn.clicked.connect(self.browse_output_dir)
output_dir_layout.addWidget(self.output_dir_input)
output_dir_layout.addWidget(self.output_dir_btn)
output_layout.addLayout(output_dir_layout)
settings_layout.addWidget(output_group)
settings_layout.addStretch()
settings_scroll.setWidget(settings_widget)
right_layout.addWidget(settings_scroll)
# Progress bar
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
right_layout.addWidget(self.progress_bar)
# Status label
self.status_label = QLabel("")
right_layout.addWidget(self.status_label)
# Process button
self.process_btn = QPushButton("Process Images")
self.process_btn.setMinimumHeight(40)
self.process_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
font-size: 14px;
font-weight: bold;
border-radius: 5px;
}
QPushButton:hover {
background-color: #45a049;
}
QPushButton:disabled {
background-color: #cccccc;
}
""")
self.process_btn.clicked.connect(self.start_processing)
right_layout.addWidget(self.process_btn)
# Add panels to main layout with splitter
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.addWidget(left_panel)
splitter.addWidget(right_panel)
splitter.setSizes([300, 600])
main_layout.addWidget(splitter)
def connect_signals(self):
"""Connect signals to slots."""
self.drop_zone.files_dropped.connect(self.add_files)
self.file_list.itemSelectionChanged.connect(self.on_selection_changed)
def toggle_resize_options(self, enabled: bool):
"""Enable or disable resize options."""
self.percentage_radio.setEnabled(enabled)
self.percentage_combo.setEnabled(enabled)
self.max_dim_radio.setEnabled(enabled)
self.max_dim_spin.setEnabled(enabled)
self.custom_radio.setEnabled(enabled)
self.width_spin.setEnabled(enabled)
self.height_spin.setEnabled(enabled)
self.maintain_aspect.setEnabled(enabled)
if enabled and self.percentage_combo.currentText() == "Custom":
self.percentage_spin.setEnabled(True)
else:
self.percentage_spin.setEnabled(False)
def on_percentage_changed(self, text: str):
"""Handle percentage combo box change."""
self.percentage_spin.setEnabled(text == "Custom" and self.resize_checkbox.isChecked())
def browse_files(self):
"""Open file dialog to select images."""
files, _ = QFileDialog.getOpenFileNames(
self,
"Select Images",
"",
"Images (*.jpg *.jpeg *.png *.gif *.bmp *.webp *.tiff);;All Files (*)"
)
if files:
self.add_files(files)
def browse_output_dir(self):
"""Open dialog to select output directory."""
directory = QFileDialog.getExistingDirectory(self, "Select Output Folder")
if directory:
self.output_dir_input.setText(directory)
def add_files(self, files: list):
"""Add files to the list."""
for file_path in files:
if file_path not in self.files:
self.files.append(file_path)
item = QListWidgetItem(os.path.basename(file_path))
item.setData(Qt.ItemDataRole.UserRole, file_path)
item.setToolTip(file_path)
self.file_list.addItem(item)
self.status_label.setText(f"{len(self.files)} file(s) ready")
# Select first item and show preview
if self.file_list.count() > 0 and not self.file_list.selectedItems():
self.file_list.setCurrentRow(0)
def remove_selected(self):
"""Remove selected files from the list."""
for item in self.file_list.selectedItems():
file_path = item.data(Qt.ItemDataRole.UserRole)
self.files.remove(file_path)
self.file_list.takeItem(self.file_list.row(item))
self.status_label.setText(f"{len(self.files)} file(s) ready")
if len(self.files) == 0:
self.preview.clear_preview()
def clear_files(self):
"""Clear all files from the list."""
self.files.clear()
self.file_list.clear()
self.preview.clear_preview()
self.status_label.setText("")
def on_selection_changed(self):
"""Handle file selection change."""
selected = self.file_list.selectedItems()
if selected:
file_path = selected[0].data(Qt.ItemDataRole.UserRole)
self.preview.load_preview(file_path, self.get_settings())
def update_preview(self):
"""Update the preview when settings change."""
selected = self.file_list.selectedItems()
if selected:
file_path = selected[0].data(Qt.ItemDataRole.UserRole)
self.preview.load_preview(file_path, self.get_settings())
def get_settings(self) -> dict:
"""Get current settings as a dictionary."""
# Get percentage value
percentage_text = self.percentage_combo.currentText()
if percentage_text == "Custom":
percentage = self.percentage_spin.value()
else:
percentage = int(percentage_text.replace("%", ""))
# Determine resize mode
if self.percentage_radio.isChecked():
resize_mode = 'percentage'
elif self.max_dim_radio.isChecked():
resize_mode = 'max_dimension'
else:
resize_mode = 'custom'
# Get output directory
output_dir = self.output_dir_input.text()
if not output_dir and self.files:
output_dir = os.path.dirname(self.files[0])
return {
'quality': self.quality_slider.value(),
'resize_enabled': self.resize_checkbox.isChecked(),
'resize_mode': resize_mode,
'resize_percentage': percentage,
'max_dimension': self.max_dim_spin.value(),
'custom_width': self.width_spin.value(),
'custom_height': self.height_spin.value(),
'maintain_aspect': self.maintain_aspect.isChecked(),
'format': self.format_combo.currentText(),
'suffix': self.suffix_input.text(),
'output_dir': output_dir
}
def start_processing(self):
"""Start processing the images."""
if not self.files:
QMessageBox.warning(self, "No Files", "Please add some images to process.")
return
settings = self.get_settings()
# Verify output directory
if not settings['output_dir']:
QMessageBox.warning(self, "No Output Folder",
"Please select an output folder or add files first.")
return
if not os.path.exists(settings['output_dir']):
try:
os.makedirs(settings['output_dir'])
except Exception as e:
QMessageBox.critical(self, "Error", f"Cannot create output folder: {e}")
return
# Disable UI during processing
self.process_btn.setEnabled(False)
self.process_btn.setText("Processing...")
self.progress_bar.setVisible(True)
self.progress_bar.setValue(0)
# Start processor thread
self.processor = ImageProcessor(self.files.copy(), settings)
self.processor.progress.connect(self.on_progress)
self.processor.finished_file.connect(self.on_file_finished)
self.processor.completed.connect(self.on_completed)
self.processor.error.connect(self.on_error)
self.processor.start()
def on_progress(self, value: int, filename: str):
"""Update progress bar."""
self.progress_bar.setValue(value)
self.status_label.setText(f"Processing: {filename}")
def on_file_finished(self, filename: str, original: int, new_size: int):
"""Handle individual file completion."""
saved = original - new_size
percent = (saved / original * 100) if original > 0 else 0
print(f"Processed {filename}: {PreviewWidget.format_size(original)} -> {PreviewWidget.format_size(new_size)} ({percent:.1f}% saved)")
def on_completed(self, total_original: int, total_saved: int):
"""Handle processing completion."""
self.process_btn.setEnabled(True)
self.process_btn.setText("Process Images")
self.progress_bar.setVisible(False)
percent = (total_saved / total_original * 100) if total_original > 0 else 0
QMessageBox.information(
self,
"Processing Complete",
f"All images processed successfully!\n\n"
f"Total original size: {PreviewWidget.format_size(total_original)}\n"
f"Total saved: {PreviewWidget.format_size(total_saved)} ({percent:.1f}%)"
)
self.status_label.setText(f"Complete! Saved {PreviewWidget.format_size(total_saved)}")
def on_error(self, filename: str, error: str):
"""Handle processing error."""
print(f"Error processing {filename}: {error}")
self.status_label.setText(f"Error with {filename}")
def main():
"""Main entry point."""
app = QApplication(sys.argv)
app.setStyle('Fusion') # Modern look on macOS
# Set application-wide stylesheet
app.setStyleSheet("""
QGroupBox {
font-weight: bold;
border: 1px solid #ccc;
border-radius: 5px;
margin-top: 10px;
padding-top: 10px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 10px;
padding: 0 5px;
}
""")
window = PhotoReducerApp()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()