-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1310 lines (1121 loc) · 59.1 KB
/
app.py
File metadata and controls
1310 lines (1121 loc) · 59.1 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
from __future__ import annotations
import gzip
import hashlib
import os
import shutil
import sys
import tarfile
import zipfile
from io import BytesIO
from pathlib import Path
from tkinter import END, BooleanVar, StringVar, Tk, filedialog, messagebox, ttk
from tkinter.scrolledtext import ScrolledText
from PIL import Image, ImageTk
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
except ImportError:
DND_FILES = None
TkinterDnD = None
try:
import imagequant
except ImportError:
imagequant = None
try:
import zopfli.png as zopfli_png
except ImportError:
zopfli_png = None
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff"}
ARCHIVE_FILE_TYPES = [
("Archive Files", "*.zip *.tar.gz *.tgz *.tar.xz *.txz *.gz"),
("All Files", "*.*"),
]
THUMBNAIL_SIZE = (120, 120)
PREVIEW_LIMIT = 8
PNG_STANDARD_MODE = "标准 PNG"
PNG_TINIFY_MODE = "Tinify-like PNG"
RESIZE_KEEP_MODE = "不调整"
RESIZE_PERCENT_MODE = "按百分比"
RESIZE_MAX_EDGE_MODE = "按最长边"
RESIZE_CUSTOM_MODE = "自定义宽高"
TINIFY_LIKE_PARAMS = {
"max_colors": 256,
"dithering_level": 0.0,
"min_quality": 40,
"max_quality": 90,
}
def format_size(size: int) -> str:
units = ["B", "KB", "MB", "GB", "TB"]
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{value:.2f} {unit}"
value /= 1024
return f"{size} B"
def hash_file(file_path: Path, algorithm: str) -> str:
hasher = hashlib.new(algorithm)
with file_path.open("rb") as handle:
while chunk := handle.read(1024 * 1024):
hasher.update(chunk)
return hasher.hexdigest()
def compress_single_file_gz(source: Path, target: Path) -> None:
with source.open("rb") as src, gzip.open(target, "wb", compresslevel=9) as dst:
while chunk := src.read(1024 * 1024):
dst.write(chunk)
def decompress_single_file_gz(source: Path, target: Path) -> None:
with gzip.open(source, "rb") as src, target.open("wb") as dst:
shutil.copyfileobj(src, dst, length=1024 * 1024)
def save_png_standard(image: Image.Image, output_path: Path) -> None:
image.save(output_path, format="PNG", optimize=True, compress_level=9)
def save_png_tinify_like(image: Image.Image, output_path: Path) -> None:
if imagequant is None:
raise RuntimeError("缺少 imagequant 依赖,无法启用 Tinify-like PNG 模式。")
rgba_image = image.convert("RGBA")
quantized = imagequant.quantize_pil_image(
rgba_image,
dithering_level=TINIFY_LIKE_PARAMS["dithering_level"],
max_colors=TINIFY_LIKE_PARAMS["max_colors"],
min_quality=TINIFY_LIKE_PARAMS["min_quality"],
max_quality=TINIFY_LIKE_PARAMS["max_quality"],
)
buffer = BytesIO()
quantized.save(buffer, format="PNG", optimize=True, compress_level=9)
png_data = buffer.getvalue()
if zopfli_png is not None:
png_data = zopfli_png.optimize(png_data, num_iterations=8, num_iterations_large=3)
output_path.write_bytes(png_data)
def find_image_files(folder: Path, recursive: bool = True) -> list[Path]:
iterator = folder.rglob("*") if recursive else folder.glob("*")
return sorted(path for path in iterator if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS)
def find_regular_files(folder: Path, recursive: bool = True) -> list[Path]:
iterator = folder.rglob("*") if recursive else folder.glob("*")
return sorted(path for path in iterator if path.is_file())
def archive_kind(file_path: Path) -> str | None:
name = file_path.name.lower()
if name.endswith(".zip"):
return "zip"
if name.endswith((".tar.gz", ".tgz")):
return "tar.gz"
if name.endswith((".tar.xz", ".txz")):
return "tar.xz"
if name.endswith(".gz"):
return "gz"
return None
def archive_display_stem(file_path: Path) -> str:
name = file_path.name
lower_name = name.lower()
for suffix in (".tar.gz", ".tar.xz", ".tgz", ".txz", ".zip", ".gz"):
if lower_name.endswith(suffix):
return name[: -len(suffix)] or file_path.stem
return file_path.stem
def safe_destination(output_dir: Path, member_name: str) -> Path:
target = output_dir / member_name
resolved_output = output_dir.resolve()
resolved_target = target.resolve(strict=False)
if not resolved_target.is_relative_to(resolved_output):
raise RuntimeError(f"压缩包包含不安全路径:{member_name}")
return target
def infer_base_dir(collected_files: list[Path], dropped_paths: list[Path]) -> Path | None:
if len(dropped_paths) == 1 and dropped_paths[0].is_dir():
return dropped_paths[0]
if len(collected_files) == 1:
return collected_files[0].parent
if collected_files:
common = Path(os.path.commonpath([str(path) for path in collected_files]))
return common if common.is_dir() else common.parent
return None
def modify_file_md5(source: Path, output: Path) -> tuple[str, str]:
"""复制文件并追加随机字节以改变 MD5,返回 (原始MD5, 新MD5)。"""
original_md5 = hash_file(source, "md5")
data = source.read_bytes()
output.write_bytes(data + os.urandom(16))
new_md5 = hash_file(output, "md5")
return original_md5, new_md5
class CompressApp:
def __init__(self, root: Tk) -> None:
self.root = root
self.root.title("压缩工具箱 Pro")
self.root.geometry("1180x860")
self.root.minsize(980, 740)
self.image_files: list[Path] = []
self.image_base_dir: Path | None = None
self.file_items: list[Path] = []
self.file_base_dir: Path | None = None
self.extract_archive_path: Path | None = None
self.extract_output_dir: Path | None = None
self.hash_file_path: Path | None = None
self.md5_files: list[Path] = []
self.md5_base_dir: Path | None = None
self.thumbnail_refs: list[ImageTk.PhotoImage] = []
self.app_icon_photo: ImageTk.PhotoImage | None = None
self.checkbox_label_vars: list[StringVar] = []
self.image_quality = StringVar(value="80")
self.image_output_format = StringVar(value="保持原格式")
self.png_mode = StringVar(
value=PNG_TINIFY_MODE if imagequant is not None else PNG_STANDARD_MODE
)
self.resize_mode = StringVar(value=RESIZE_KEEP_MODE)
self.resize_value = StringVar(value="100")
self.resize_width = StringVar(value="800")
self.resize_height = StringVar(value="600")
self.lock_aspect_ratio = BooleanVar(value=False)
self.archive_format = StringVar(value="zip")
self.extract_summary = StringVar(value="未选择压缩包")
self.extract_output_summary = StringVar(value="默认输出到压缩包旁边的 *_extracted 文件夹")
self.image_recursive = BooleanVar(value=True)
self.file_recursive = BooleanVar(value=True)
self.status_text = StringVar(value="准备就绪")
self.drag_hint = StringVar(
value="将文件或文件夹拖到窗口中;会按当前页签自动分发到图片压缩、文件压缩或哈希计算。"
)
self._resize_trace_guard = False
self._configure_styles()
self._set_window_icon()
self._build_layout()
self._bind_resize_traces()
self._enable_drag_drop()
def _configure_styles(self) -> None:
self.root.configure(bg="#eef3f8")
style = ttk.Style()
try:
style.theme_use("clam")
except Exception:
pass
style.configure(".", font=("SF Pro Text", 12))
style.configure("App.TFrame", background="#eef3f8")
style.configure("Hero.TFrame", background="#0b1220")
style.configure("HeroBadge.TFrame", background="#172554")
style.configure("Card.TFrame", background="#ffffff")
style.configure("Drop.TFrame", background="#15233b")
style.configure("Panel.TFrame", background="#eef3f8")
style.configure("Section.TFrame", background="#ffffff")
style.configure("Preview.TFrame", background="#f8fbff")
style.configure("Thumb.TFrame", background="#ffffff")
style.configure("Preview.TLabel", background="#ffffff")
style.configure("HeroTitle.TLabel", background="#0b1220", foreground="#f8fafc", font=("SF Pro Display", 27, "bold"))
style.configure("HeroSub.TLabel", background="#0b1220", foreground="#cbd5e1", font=("SF Pro Text", 12))
style.configure("HeroMeta.TLabel", background="#172554", foreground="#bfdbfe", font=("SF Pro Text", 11, "bold"))
style.configure("DropTitle.TLabel", background="#15233b", foreground="#f8fafc", font=("SF Pro Display", 13, "bold"))
style.configure("DropText.TLabel", background="#15233b", foreground="#bfdbfe", font=("SF Pro Text", 11))
style.configure("CardTitle.TLabel", background="#ffffff", foreground="#64748b", font=("SF Pro Text", 10, "bold"))
style.configure("CardValue.TLabel", background="#ffffff", foreground="#0f172a", font=("SF Pro Display", 17, "bold"))
style.configure("PanelTitle.TLabel", background="#eef3f8", foreground="#0f172a", font=("SF Pro Display", 20, "bold"))
style.configure("PanelText.TLabel", background="#eef3f8", foreground="#64748b", font=("SF Pro Text", 11))
style.configure("SectionTitle.TLabel", background="#ffffff", foreground="#0f172a", font=("SF Pro Display", 14, "bold"))
style.configure("SectionText.TLabel", background="#ffffff", foreground="#64748b", font=("SF Pro Text", 11))
style.configure("Check.TLabel", background="#ffffff", foreground="#334155", font=("SF Pro Text", 11, "bold"))
style.configure("FieldLabel.TLabel", background="#ffffff", foreground="#334155", font=("SF Pro Text", 11, "bold"))
style.configure("PreviewTitle.TLabel", background="#f8fbff", foreground="#0f172a", font=("SF Pro Display", 13, "bold"))
style.configure("PreviewText.TLabel", background="#f8fbff", foreground="#64748b", font=("SF Pro Text", 10))
style.configure("PreviewName.TLabel", background="#ffffff", foreground="#1e293b", font=("SF Pro Text", 10, "bold"))
style.configure("Status.TLabel", background="#eef3f8", foreground="#2563eb", font=("SF Pro Text", 11, "bold"))
style.configure("Primary.TButton", font=("SF Pro Text", 11, "bold"), padding=(16, 10), foreground="#ffffff", background="#2563eb", borderwidth=0)
style.map("Primary.TButton", background=[("active", "#1d4ed8"), ("pressed", "#1e40af")])
style.configure("Secondary.TButton", font=("SF Pro Text", 11, "bold"), padding=(13, 9), foreground="#1e293b", background="#e2e8f0", borderwidth=0)
style.map("Secondary.TButton", background=[("active", "#cbd5e1"), ("pressed", "#94a3b8")])
style.configure("TNotebook", background="#eef3f8", borderwidth=0)
style.configure("TNotebook.Tab", padding=(22, 12), font=("SF Pro Text", 11, "bold"), background="#dbe5f0", foreground="#475569")
style.map("TNotebook.Tab", background=[("selected", "#ffffff"), ("active", "#eaf0f7")], foreground=[("selected", "#0f172a")])
style.configure("Section.TCheckbutton", background="#ffffff", foreground="#334155", font=("SF Pro Text", 11))
style.configure("TCombobox", padding=6)
style.configure("TEntry", padding=6)
def _set_window_icon(self) -> None:
icon_path = self._resource_path("icon.png")
if not icon_path.exists():
return
try:
with Image.open(icon_path) as image:
icon = image.copy()
icon.thumbnail((256, 256))
self.app_icon_photo = ImageTk.PhotoImage(icon)
self.root.iconphoto(True, self.app_icon_photo)
except Exception:
return
def _resource_path(self, relative_path: str) -> Path:
base_dir = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
return base_dir / relative_path
def _build_layout(self) -> None:
app = ttk.Frame(self.root, style="App.TFrame", padding=18)
app.pack(fill="both", expand=True)
header = ttk.Frame(app, style="Hero.TFrame", padding=(22, 18))
header.pack(fill="x", pady=(0, 14))
header.columnconfigure(0, weight=1)
header.columnconfigure(1, weight=0)
hero_copy = ttk.Frame(header, style="Hero.TFrame")
hero_copy.grid(row=0, column=0, sticky="nsew")
ttk.Label(hero_copy, text="压缩工具箱 Pro", style="HeroTitle.TLabel").pack(anchor="w")
ttk.Label(
hero_copy,
text="一个清爽的本地处理工作台:图片压缩、文件归档、哈希校验和 MD5 改写都在同一个界面完成。",
style="HeroSub.TLabel",
wraplength=680,
).pack(anchor="w", pady=(8, 14))
badge_row = ttk.Frame(hero_copy, style="Hero.TFrame")
badge_row.pack(anchor="w")
for text in ["本地处理", "批量递归", "拖拽导入", "无云端上传"]:
badge = ttk.Frame(badge_row, style="HeroBadge.TFrame", padding=(10, 5))
badge.pack(side="left", padx=(0, 8))
ttk.Label(badge, text=text, style="HeroMeta.TLabel").pack()
drop_banner = ttk.Frame(header, style="Drop.TFrame", padding=(18, 14))
drop_banner.grid(row=0, column=1, sticky="nsew", padx=(18, 0))
ttk.Label(drop_banner, text="拖拽工作区", style="DropTitle.TLabel").pack(anchor="w")
self.drop_banner_text = ttk.Label(drop_banner, textvariable=self.drag_hint, style="DropText.TLabel", wraplength=310)
self.drop_banner_text.pack(anchor="w", pady=(6, 0))
self.drop_targets = [self.root, self.drop_banner_text]
stats = ttk.Frame(app, style="App.TFrame")
stats.pack(fill="x", pady=(0, 14))
self._build_stat_card(stats, "图片任务", "未选择", 0)
self._build_stat_card(stats, "归档任务", "未选择", 1)
self._build_stat_card(stats, "MD5 任务", "未选择", 2)
self._build_stat_card(stats, "当前状态", "准备就绪", 3)
self.notebook = ttk.Notebook(app)
self.notebook.pack(fill="both", expand=True)
self.image_log = self._build_image_tab(self.notebook)
self.archive_log = self._build_archive_tab(self.notebook)
self.hash_output = self._build_hash_tab(self.notebook)
self.md5_log = self._build_md5_modify_tab(self.notebook)
footer = ttk.Frame(app, style="App.TFrame")
footer.pack(fill="x", pady=(10, 0))
ttk.Label(footer, textvariable=self.status_text, style="Status.TLabel").pack(anchor="w")
def _build_stat_card(self, parent: ttk.Frame, title: str, value: str, column: int) -> None:
card = ttk.Frame(parent, style="Card.TFrame", padding=(16, 13))
card.grid(row=0, column=column, sticky="nsew", padx=(0, 12) if column < 3 else 0)
parent.columnconfigure(column, weight=1)
value_var = StringVar(value=value)
ttk.Label(card, text=title, style="CardTitle.TLabel").pack(anchor="w")
ttk.Label(card, textvariable=value_var, style="CardValue.TLabel").pack(anchor="w", pady=(7, 0))
if column == 0:
self.image_stat = value_var
elif column == 1:
self.archive_stat = value_var
elif column == 2:
self.md5_stat = value_var
else:
self.run_stat = value_var
def _build_panel(self, notebook: ttk.Notebook, title: str, note: str) -> ttk.Frame:
panel = ttk.Frame(notebook, style="Panel.TFrame", padding=(16, 18))
notebook.add(panel, text=title)
ttk.Label(panel, text=title, style="PanelTitle.TLabel").pack(anchor="w")
ttk.Label(panel, text=note, style="PanelText.TLabel", wraplength=980).pack(anchor="w", pady=(5, 14))
return panel
def _build_section(self, parent: ttk.Frame, title: str, note: str | None = None) -> ttk.Frame:
section = ttk.Frame(parent, style="Section.TFrame", padding=(16, 14))
section.pack(fill="x", pady=(0, 12))
ttk.Label(section, text=title, style="SectionTitle.TLabel").pack(anchor="w")
if note:
ttk.Label(section, text=note, style="SectionText.TLabel", wraplength=960).pack(anchor="w", pady=(4, 0))
return section
def _build_log_section(self, parent: ttk.Frame, title: str) -> ScrolledText:
section = ttk.Frame(parent, style="Section.TFrame", padding=(16, 14))
section.pack(fill="both", expand=True)
ttk.Label(section, text=title, style="SectionTitle.TLabel").pack(anchor="w", pady=(0, 10))
return self._make_log(section)
def _build_field_label(self, parent: ttk.Frame, text: str, row: int, column: int) -> None:
ttk.Label(parent, text=text, style="FieldLabel.TLabel").grid(row=row, column=column, sticky="w", padx=(0, 8), pady=6)
def _make_checkbutton(self, parent: ttk.Frame, text: str, variable: BooleanVar):
label_var = StringVar()
def refresh_label(*_args) -> None:
label_var.set(f"{'☑' if variable.get() else '☐'} {text}")
def toggle(_event=None) -> str:
variable.set(not variable.get())
return "break"
refresh_label()
variable.trace_add("write", refresh_label)
self.checkbox_label_vars.append(label_var)
label = ttk.Label(parent, textvariable=label_var, style="Check.TLabel", cursor="pointinghand", padding=(2, 4))
label.bind("<Button-1>", toggle)
label.bind("<space>", toggle)
label.bind("<Return>", toggle)
label.configure(takefocus=True)
return label
def _build_image_tab(self, notebook: ttk.Notebook) -> ScrolledText:
panel = self._build_panel(
notebook,
"图片压缩",
"支持选多张图片,也支持直接选整个图片文件夹递归压缩。压缩后保留原文件名,输出到对应目录下的 compressed_output 文件夹。",
)
source_section = self._build_section(panel, "选择来源", "可选择单张/多张图片,也可以选择文件夹批量处理。")
source_row = ttk.Frame(source_section, style="Section.TFrame")
source_row.pack(fill="x", pady=(12, 8))
ttk.Button(source_row, text="选择图片", style="Secondary.TButton", command=self.choose_images).pack(side="left")
ttk.Button(source_row, text="选择图片文件夹", style="Secondary.TButton", command=self.choose_image_folder).pack(side="left", padx=8)
self._make_checkbutton(source_row, "递归扫描子文件夹", self.image_recursive).pack(side="left", padx=10)
self.image_summary = StringVar(value="未选择图片或文件夹")
ttk.Label(source_section, textvariable=self.image_summary, style="SectionText.TLabel").pack(anchor="w")
options_section = self._build_section(panel, "压缩设置", "常用参数分组展示,避免横向拥挤。")
options_grid = ttk.Frame(options_section, style="Section.TFrame")
options_grid.pack(fill="x", pady=(12, 0))
for column in (1, 3, 5, 7):
options_grid.columnconfigure(column, weight=1)
self._build_field_label(options_grid, "压缩质量", 0, 0)
ttk.Combobox(
options_grid,
textvariable=self.image_quality,
values=["95", "90", "85", "80", "75", "70", "60", "50"],
width=8,
state="readonly",
).grid(row=0, column=1, sticky="ew", padx=(0, 18), pady=6)
self._build_field_label(options_grid, "输出格式", 0, 2)
ttk.Combobox(
options_grid,
textvariable=self.image_output_format,
values=["保持原格式", "JPEG", "WEBP", "PNG"],
width=12,
state="readonly",
).grid(row=0, column=3, sticky="ew", padx=(0, 18), pady=6)
self._build_field_label(options_grid, "PNG 模式", 0, 4)
ttk.Combobox(
options_grid,
textvariable=self.png_mode,
values=[PNG_STANDARD_MODE, PNG_TINIFY_MODE],
width=16,
state="readonly",
).grid(row=0, column=5, sticky="ew", padx=(0, 18), pady=6)
self._build_field_label(options_grid, "尺寸调整", 0, 6)
ttk.Combobox(
options_grid,
textvariable=self.resize_mode,
values=[RESIZE_KEEP_MODE, RESIZE_PERCENT_MODE, RESIZE_MAX_EDGE_MODE, RESIZE_CUSTOM_MODE],
width=10,
state="readonly",
).grid(row=0, column=7, sticky="ew", pady=6)
self._build_field_label(options_grid, "参数值", 1, 0)
ttk.Entry(options_grid, textvariable=self.resize_value, width=10).grid(row=1, column=1, sticky="ew", padx=(0, 18), pady=6)
self._build_field_label(options_grid, "目标宽度", 1, 2)
ttk.Entry(options_grid, textvariable=self.resize_width, width=10).grid(row=1, column=3, sticky="ew", padx=(0, 18), pady=6)
self._build_field_label(options_grid, "目标高度", 1, 4)
ttk.Entry(options_grid, textvariable=self.resize_height, width=10).grid(row=1, column=5, sticky="ew", padx=(0, 18), pady=6)
self._make_checkbutton(options_grid, "锁定宽高比", self.lock_aspect_ratio).grid(row=1, column=6, sticky="w", pady=6)
ttk.Button(options_grid, text="开始压缩", style="Primary.TButton", command=self.compress_images).grid(row=1, column=7, sticky="e", pady=6)
self.png_mode_note = StringVar()
self._refresh_png_mode_note()
ttk.Label(options_section, textvariable=self.png_mode_note, style="SectionText.TLabel").pack(anchor="w", pady=(10, 0))
ttk.Label(
options_section,
text="尺寸调整支持按百分比缩放、限制最长边,或自定义宽高。未锁定宽高比时,自定义尺寸会自动拉伸。",
style="SectionText.TLabel",
).pack(anchor="w", pady=(4, 0))
preview_panel = ttk.Frame(panel, style="Preview.TFrame", padding=(16, 14))
preview_panel.pack(fill="x", pady=(0, 12))
ttk.Label(preview_panel, text="图片预览", style="PreviewTitle.TLabel").pack(anchor="w")
self.preview_summary = StringVar(value="选择图片后会在这里显示缩略图")
ttk.Label(preview_panel, textvariable=self.preview_summary, style="PreviewText.TLabel").pack(anchor="w", pady=(4, 10))
self.preview_grid = ttk.Frame(preview_panel, style="Preview.TFrame")
self.preview_grid.pack(fill="x")
return self._build_log_section(panel, "处理日志")
def _build_archive_tab(self, notebook: ttk.Notebook) -> ScrolledText:
panel = self._build_panel(
notebook,
"文件压缩 / 解压",
"支持多文件归档、文件夹打包,也支持 zip、tar.gz、tar.xz 和单文件 gz 解压。",
)
source_section = self._build_section(panel, "压缩来源", "适合将零散文件或整个项目目录打包为压缩归档。")
source_row = ttk.Frame(source_section, style="Section.TFrame")
source_row.pack(fill="x", pady=(12, 8))
ttk.Button(source_row, text="选择文件", style="Secondary.TButton", command=self.choose_files).pack(side="left")
ttk.Button(source_row, text="选择文件夹", style="Secondary.TButton", command=self.choose_file_folder).pack(side="left", padx=8)
self._make_checkbutton(source_row, "递归扫描子文件夹", self.file_recursive).pack(side="left", padx=10)
self.file_summary = StringVar(value="未选择文件或文件夹")
ttk.Label(source_section, textvariable=self.file_summary, style="SectionText.TLabel").pack(anchor="w")
options_section = self._build_section(panel, "归档设置")
options_row = ttk.Frame(options_section, style="Section.TFrame")
options_row.pack(fill="x", pady=(12, 0))
ttk.Label(options_row, text="压缩格式", style="FieldLabel.TLabel").pack(side="left")
ttk.Combobox(
options_row,
textvariable=self.archive_format,
values=["zip", "tar.gz", "tar.xz", "gz(单文件)"],
width=12,
state="readonly",
).pack(side="left", padx=(8, 0))
ttk.Button(options_row, text="开始归档", style="Primary.TButton", command=self.compress_files).pack(side="right")
extract_section = self._build_section(panel, "解压设置", "选择压缩包后可直接解压;未指定输出目录时,会自动创建 *_extracted 文件夹。")
extract_row = ttk.Frame(extract_section, style="Section.TFrame")
extract_row.pack(fill="x", pady=(12, 8))
ttk.Button(extract_row, text="选择压缩包", style="Secondary.TButton", command=self.choose_extract_archive).pack(side="left")
ttk.Button(extract_row, text="选择输出目录", style="Secondary.TButton", command=self.choose_extract_output_dir).pack(side="left", padx=8)
ttk.Button(extract_row, text="开始解压", style="Primary.TButton", command=self.extract_archive).pack(side="right")
ttk.Label(extract_section, textvariable=self.extract_summary, style="SectionText.TLabel").pack(anchor="w")
ttk.Label(extract_section, textvariable=self.extract_output_summary, style="SectionText.TLabel").pack(anchor="w", pady=(4, 0))
return self._build_log_section(panel, "归档 / 解压日志")
def _build_hash_tab(self, notebook: ttk.Notebook) -> ScrolledText:
panel = self._build_panel(
notebook,
"哈希计算",
"提供 MD5 / SHA1 / SHA256 校验值计算,方便做文件校验或整理记录。",
)
source_section = self._build_section(panel, "选择文件", "选择或拖入一个文件,即可一次得到三种常用哈希值。")
source_row = ttk.Frame(source_section, style="Section.TFrame")
source_row.pack(fill="x", pady=(12, 8))
ttk.Button(source_row, text="选择文件", style="Secondary.TButton", command=self.choose_hash_file).pack(side="left")
ttk.Button(source_row, text="计算哈希", style="Primary.TButton", command=self.calculate_hashes).pack(side="right")
self.hash_summary = StringVar(value="未选择文件")
ttk.Label(source_section, textvariable=self.hash_summary, style="SectionText.TLabel").pack(anchor="w")
return self._build_log_section(panel, "哈希结果")
def _build_md5_modify_tab(self, notebook: ttk.Notebook) -> ScrolledText:
panel = self._build_panel(
notebook,
"MD5 改写",
"在不影响文件内容显示的前提下修改其 MD5 值。输出到同目录下的 md5_modified 文件夹。",
)
source_section = self._build_section(panel, "选择来源", "会复制文件并追加随机字节,原文件不会被覆盖。")
source_row = ttk.Frame(source_section, style="Section.TFrame")
source_row.pack(fill="x", pady=(12, 8))
ttk.Button(source_row, text="选择文件", style="Secondary.TButton", command=self.choose_md5_files).pack(side="left")
ttk.Button(source_row, text="选择文件夹", style="Secondary.TButton", command=self.choose_md5_folder).pack(side="left", padx=8)
self._make_checkbutton(source_row, "递归扫描子文件夹", self.file_recursive).pack(side="left", padx=10)
self.md5_summary = StringVar(value="未选择文件")
ttk.Label(source_section, textvariable=self.md5_summary, style="SectionText.TLabel").pack(anchor="w")
action_row = self._build_section(panel, "执行处理")
ttk.Button(action_row, text="开始处理", style="Primary.TButton", command=self.modify_file_md5s).pack(side="right")
return self._build_log_section(panel, "处理日志")
def _make_log(self, parent: ttk.Frame) -> ScrolledText:
log = ScrolledText(
parent,
height=14,
font=("SF Mono", 11),
bg="#0b1220",
fg="#dbeafe",
insertbackground="#ffffff",
relief="flat",
padx=12,
pady=12,
)
log.pack(fill="both", expand=True)
return log
def _enable_drag_drop(self) -> None:
if not DND_FILES:
self.drag_hint.set("拖拽功能需要安装 `tkinterdnd2`;当前仍可用按钮选择文件或文件夹。")
return
for widget in self.drop_targets:
widget.drop_target_register(DND_FILES)
widget.dnd_bind("<<Drop>>", self.handle_drop)
def _bind_resize_traces(self) -> None:
self.resize_width.trace_add("write", self._on_resize_width_changed)
self.resize_height.trace_add("write", self._on_resize_height_changed)
def _on_resize_width_changed(self, *_args) -> None:
self._sync_custom_resize_fields("width")
def _on_resize_height_changed(self, *_args) -> None:
self._sync_custom_resize_fields("height")
def _sync_custom_resize_fields(self, changed_field: str) -> None:
if self._resize_trace_guard:
return
if self.resize_mode.get() != RESIZE_CUSTOM_MODE or not self.lock_aspect_ratio.get():
return
ratio = self._reference_image_ratio()
if ratio is None:
return
try:
if changed_field == "width":
width = int(self.resize_width.get().strip())
if width <= 0:
return
height = max(1, round(width / ratio))
self._resize_trace_guard = True
self.resize_height.set(str(height))
else:
height = int(self.resize_height.get().strip())
if height <= 0:
return
width = max(1, round(height * ratio))
self._resize_trace_guard = True
self.resize_width.set(str(width))
except ValueError:
return
finally:
self._resize_trace_guard = False
def _reference_image_ratio(self) -> float | None:
if not self.image_files:
return None
try:
with Image.open(self.image_files[0]) as image:
width, height = image.size
except Exception:
return None
if height == 0:
return None
return width / height
def _set_status(self, message: str) -> None:
self.status_text.set(message)
self.run_stat.set(message)
def _refresh_png_mode_note(self) -> None:
if imagequant is None:
self.png_mode_note.set("`Tinify-like PNG` 需要安装 `imagequant`;当前会自动使用标准 PNG 压缩。")
return
if zopfli_png is None:
self.png_mode_note.set("当前可用 `imagequant` 调色板量化;未检测到 `zopfli` 时会跳过后置 PNG 深度优化。")
return
self.png_mode_note.set("`Tinify-like PNG` 使用 256 色量化、无抖动、质量 40~90,并追加 zopfli 优化。")
def choose_images(self) -> None:
selected = filedialog.askopenfilenames(
title="选择图片",
filetypes=[("Image Files", "*.jpg *.jpeg *.png *.webp *.bmp *.tiff"), ("All Files", "*.*")],
)
self._apply_image_selection([Path(item) for item in selected], base_dir=None)
def choose_image_folder(self) -> None:
selected = filedialog.askdirectory(title="选择图片文件夹")
if not selected:
return
folder = Path(selected)
images = find_image_files(folder, recursive=self.image_recursive.get())
self._apply_image_selection(images, base_dir=folder, source_label=f"文件夹 {folder.name}")
def choose_files(self) -> None:
selected = filedialog.askopenfilenames(title="选择文件", filetypes=[("All Files", "*.*")])
self._apply_file_selection([Path(item) for item in selected], base_dir=None)
def choose_file_folder(self) -> None:
selected = filedialog.askdirectory(title="选择文件夹")
if not selected:
return
folder = Path(selected)
files = find_regular_files(folder, recursive=self.file_recursive.get())
self._apply_file_selection(files, base_dir=folder, source_label=f"文件夹 {folder.name}")
def choose_extract_archive(self) -> None:
selected = filedialog.askopenfilename(title="选择压缩包", filetypes=ARCHIVE_FILE_TYPES)
if not selected:
return
self._apply_extract_archive(Path(selected))
def choose_extract_output_dir(self) -> None:
selected = filedialog.askdirectory(title="选择解压输出目录")
if not selected:
return
self.extract_output_dir = Path(selected)
self.extract_output_summary.set(f"输出目录:{self.extract_output_dir}")
self._set_status("已选择解压输出目录")
def choose_hash_file(self) -> None:
selected = filedialog.askopenfilename(title="选择文件", filetypes=[("All Files", "*.*")])
self.hash_file_path = Path(selected) if selected else None
if self.hash_file_path:
self.hash_summary.set(str(self.hash_file_path))
self._set_status("已选择哈希文件")
else:
self.hash_summary.set("未选择文件")
def _apply_image_selection(self, image_files: list[Path], base_dir: Path | None, source_label: str | None = None) -> None:
self.image_files = sorted(image_files)
self.image_base_dir = base_dir
if self.image_files:
label = source_label or "已选择图片"
self.image_summary.set(f"{label},共 {len(self.image_files)} 张")
self.image_stat.set(f"{len(self.image_files)} 张")
self._set_status("已载入图片列表")
else:
self.image_summary.set("未选择图片或文件夹")
self.image_stat.set("未选择")
self.refresh_preview()
def _apply_file_selection(self, files: list[Path], base_dir: Path | None, source_label: str | None = None) -> None:
self.file_items = sorted(files)
self.file_base_dir = base_dir
if self.file_items:
label = source_label or "已选择文件"
self.file_summary.set(f"{label},共 {len(self.file_items)} 个")
self.archive_stat.set(f"{len(self.file_items)} 个")
self._set_status("已载入归档文件列表")
else:
self.file_summary.set("未选择文件或文件夹")
self.archive_stat.set("未选择")
def _apply_extract_archive(self, archive_path: Path) -> None:
if not archive_path.is_file():
messagebox.showwarning("提示", "请选择一个压缩包文件。")
return
kind = archive_kind(archive_path)
if kind is None:
messagebox.showwarning("提示", "暂仅支持 zip、tar.gz、tar.xz 和单文件 gz。")
return
self.extract_archive_path = archive_path
default_output = self._default_extract_output_dir(archive_path)
self.extract_summary.set(f"压缩包:{archive_path.name}({kind})")
if self.extract_output_dir is None:
self.extract_output_summary.set(f"默认输出目录:{default_output}")
self.archive_stat.set("待解压")
self._set_status("已选择待解压压缩包")
def _default_extract_output_dir(self, archive_path: Path) -> Path:
return archive_path.parent / f"{archive_display_stem(archive_path)}_extracted"
def refresh_preview(self) -> None:
for child in self.preview_grid.winfo_children():
child.destroy()
self.thumbnail_refs.clear()
if not self.image_files:
self.preview_summary.set("选择图片后会在这里显示缩略图")
return
self.preview_summary.set(f"预览前 {min(len(self.image_files), PREVIEW_LIMIT)} 张图片")
for index, image_path in enumerate(self.image_files[:PREVIEW_LIMIT]):
card = ttk.Frame(self.preview_grid, style="Preview.TFrame", padding=8)
row, column = divmod(index, 4)
card.grid(row=row, column=column, padx=6, pady=6, sticky="nw")
try:
with Image.open(image_path) as image:
thumbnail = image.copy()
thumbnail.thumbnail(THUMBNAIL_SIZE)
photo = ImageTk.PhotoImage(thumbnail)
self.thumbnail_refs.append(photo)
ttk.Label(card, image=photo, style="Preview.TLabel").pack(anchor="center")
ttk.Label(card, text=image_path.name, style="PreviewName.TLabel", width=18).pack(anchor="w", pady=(8, 2))
meta = f"{image.width}×{image.height} · {format_size(image_path.stat().st_size)}"
ttk.Label(card, text=meta, style="PreviewText.TLabel").pack(anchor="w")
except Exception:
ttk.Label(card, text=image_path.name, style="PreviewName.TLabel", width=18).pack(anchor="w")
ttk.Label(card, text="无法生成缩略图", style="PreviewText.TLabel").pack(anchor="w", pady=(6, 0))
def handle_drop(self, event) -> str:
paths = [Path(item) for item in self.root.tk.splitlist(event.data)]
selected_tab = self.notebook.tab(self.notebook.select(), "text")
if selected_tab == "图片压缩":
self._handle_image_drop(paths)
elif selected_tab.startswith("文件压缩"):
self._handle_file_drop(paths)
elif selected_tab == "MD5 改写":
self._handle_md5_drop(paths)
else:
self._handle_hash_drop(paths)
return "break"
def _handle_image_drop(self, paths: list[Path]) -> None:
images: list[Path] = []
for path in paths:
if path.is_dir():
images.extend(find_image_files(path, recursive=self.image_recursive.get()))
elif path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS:
images.append(path)
if not images:
messagebox.showwarning("提示", "拖入的内容里没有可处理的图片。")
return
base_dir = infer_base_dir(images, paths)
self._apply_image_selection(images, base_dir=base_dir, source_label="拖拽导入")
self._set_status("已通过拖拽载入图片")
def _handle_file_drop(self, paths: list[Path]) -> None:
archive = next((path for path in paths if path.is_file() and archive_kind(path) is not None), None)
if archive is not None and len(paths) == 1:
self._apply_extract_archive(archive)
self._set_status("已通过拖拽选择待解压压缩包")
return
files: list[Path] = []
for path in paths:
if path.is_dir():
files.extend(find_regular_files(path, recursive=self.file_recursive.get()))
elif path.is_file():
files.append(path)
if not files:
messagebox.showwarning("提示", "拖入的内容里没有可归档的文件。")
return
base_dir = infer_base_dir(files, paths)
self._apply_file_selection(files, base_dir=base_dir, source_label="拖拽导入")
self._set_status("已通过拖拽载入归档文件")
def _handle_hash_drop(self, paths: list[Path]) -> None:
target = next((path for path in paths if path.is_file()), None)
if not target:
messagebox.showwarning("提示", "哈希计算页只能接收单个文件。")
return
self.hash_file_path = target
self.hash_summary.set(str(target))
self._set_status("已通过拖拽选择哈希文件")
def _handle_md5_drop(self, paths: list[Path]) -> None:
files: list[Path] = []
for path in paths:
if path.is_dir():
files.extend(find_regular_files(path, recursive=self.file_recursive.get()))
elif path.is_file():
files.append(path)
if not files:
messagebox.showwarning("提示", "拖入的内容里没有可处理的文件。")
return
base_dir = infer_base_dir(files, paths)
self._apply_md5_selection(files, base_dir=base_dir, source_label="拖拽导入")
self._set_status("已通过拖拽载入 MD5 改写文件")
def choose_md5_files(self) -> None:
selected = filedialog.askopenfilenames(title="选择文件", filetypes=[("All Files", "*.*")])
self._apply_md5_selection([Path(item) for item in selected], base_dir=None)
def choose_md5_folder(self) -> None:
selected = filedialog.askdirectory(title="选择文件夹")
if not selected:
return
folder = Path(selected)
files = find_regular_files(folder, recursive=self.file_recursive.get())
self._apply_md5_selection(files, base_dir=folder, source_label=f"文件夹 {folder.name}")
def _apply_md5_selection(self, files: list[Path], base_dir: Path | None, source_label: str | None = None) -> None:
self.md5_files = sorted(files)
self.md5_base_dir = base_dir
if self.md5_files:
label = source_label or "已选择文件"
self.md5_summary.set(f"{label},共 {len(self.md5_files)} 个")
self.md5_stat.set(f"{len(self.md5_files)} 个")
self._set_status("已载入 MD5 改写文件列表")
else:
self.md5_summary.set("未选择文件")
self.md5_stat.set("未选择")
def modify_file_md5s(self) -> None:
if not self.md5_files:
messagebox.showwarning("提示", "请先选择文件。")
return
self.md5_log.delete("1.0", END)
self._set_status("正在处理 MD5 改写…")
success_count = 0
for file_path in self.md5_files:
try:
if self.md5_base_dir and file_path.is_relative_to(self.md5_base_dir):
relative_parent = file_path.parent.relative_to(self.md5_base_dir)
output_dir = self.md5_base_dir / "md5_modified" / relative_parent
else:
output_dir = file_path.parent / "md5_modified"
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / file_path.name
original_md5, new_md5 = modify_file_md5(file_path, output_path)
self.md5_log.insert(
END,
f"{file_path}\n"
f" 原始 MD5: {original_md5}\n"
f" 新 MD5: {new_md5}\n"
f" 输出: {output_path}\n\n",
)
success_count += 1
except Exception as exc:
self.md5_log.insert(END, f"{file_path}\n 失败: {exc}\n\n")
self._set_status(f"MD5 改写完成:{success_count}/{len(self.md5_files)}")
messagebox.showinfo("完成", f"MD5 改写完成:成功 {success_count} / {len(self.md5_files)}")
def compress_images(self) -> None:
if not self.image_files:
messagebox.showwarning("提示", "请先选择图片或图片文件夹。")
return
output_format = self.image_output_format.get()
png_mode = self.png_mode.get()
quality = int(self.image_quality.get())
resize_mode = self.resize_mode.get()
resize_value = self._parse_resize_value(
resize_mode,
self.resize_value.get(),
self.resize_width.get(),
self.resize_height.get(),
)
self.image_log.delete("1.0", END)
self._set_status("正在压缩图片…")
success_count = 0
for image_path in self.image_files:
try:
output_dir = self._image_output_dir(image_path)
output_dir.mkdir(parents=True, exist_ok=True)
suffix, save_format = self._resolve_image_format(image_path, output_format)
output_name = f"{image_path.stem}{suffix}"
output_path = output_dir / output_name
original_size = image_path.stat().st_size
with Image.open(image_path) as image:
self._save_compressed_image(
image=image,
output_path=output_path,
save_format=save_format,
quality=quality,
png_mode=png_mode,
resize_mode=resize_mode,
resize_value=resize_value,
lock_aspect_ratio=self.lock_aspect_ratio.get(),
)
new_size = output_path.stat().st_size
ratio = (1 - new_size / original_size) * 100 if original_size else 0
strategy_note = self._compression_strategy_label(save_format, png_mode)
resize_note = self._resize_strategy_label(resize_mode, resize_value)
self.image_log.insert(
END,
f"{image_path}\n"
f" 原始: {format_size(original_size)}\n"
f" 压缩: {format_size(new_size)}\n"
f" 变化: {ratio:+.2f}%\n"
f" 模式: {strategy_note}\n"
f" 尺寸: {resize_note}\n"
f" 输出: {output_path}\n\n",
)
success_count += 1
except Exception as exc:
self.image_log.insert(END, f"{image_path}\n 失败: {exc}\n\n")
self._set_status(f"图片压缩完成:{success_count}/{len(self.image_files)}")
messagebox.showinfo("完成", f"图片处理完成:成功 {success_count} / {len(self.image_files)}")
def _image_output_dir(self, image_path: Path) -> Path:
if self.image_base_dir and image_path.is_relative_to(self.image_base_dir):
relative_parent = image_path.parent.relative_to(self.image_base_dir)
return self.image_base_dir / "compressed_output" / relative_parent
return image_path.parent / "compressed_output"
def _save_compressed_image(
self,
image: Image.Image,
output_path: Path,
save_format: str,
quality: int,
png_mode: str,
resize_mode: str,
resize_value: int | tuple[int, int] | None,
lock_aspect_ratio: bool,
) -> None:
prepared = self._resize_image_if_needed(image, resize_mode, resize_value, lock_aspect_ratio)
if save_format == "PNG":
png_image = prepared.copy()
if png_mode == PNG_TINIFY_MODE and imagequant is not None:
save_png_tinify_like(png_image, output_path)
else:
save_png_standard(png_image, output_path)
return
converted = prepared.convert("RGB") if save_format in {"JPEG", "WEBP"} else prepared.copy()