吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1539|回复: 27
收起左侧

[Python 原创] 转换不求人,用AI做一个ICO图标文件生成器。

  [复制链接]
liuyang207 发表于 2025-3-5 19:43
本帖最后由 苏紫方璇 于 2025-3-8 23:15 编辑

微信图片_20250305194148.png

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
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
import tkinter as tk
from tkinter import filedialog
from PIL import Image
import os
 
# 支持的图像文件扩展名
SUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.gif', '.bmp')
 
def convert_image_to_ico(image_path):
    # 检测文件是否存在
    if not os.path.exists(image_path):
        file_name = os.path.basename(image_path)
        error_msg = f"错误:文件 {file_name} 不存在。"
        result_label.config(text=error_msg)
        return
 
    # 检查文件扩展名是否在支持列表中
    if not any(image_path.lower().endswith(ext) for ext in SUPPORTED_EXTENSIONS):
        file_name = os.path.basename(image_path)
        error_msg = f"错误:{file_name} 不是支持的图像文件格式。支持的格式有:{', '.join(SUPPORTED_EXTENSIONS)}"
        result_label.config(text=error_msg)
        return
 
    try:
        # 尝试打开图像以检测是否为有效的图像文件
        image = Image.open(image_path)
 
        # 检查图像尺寸是否过小
        if image.width < 256 or image.height < 256:
            file_name = os.path.basename(image_path)
            error_msg = f"错误:{file_name} 图像尺寸太小,无法生成 256x256 的 ICO 文件。"
            result_label.config(text=error_msg)
            return
 
        # 获取图像文件的文件名(不包含扩展名)
        file_name_without_ext = os.path.splitext(os.path.basename(image_path))[0]
 
        # 定义 ICO 文件的保存路径
        ico_path = os.path.join(os.path.dirname(image_path), f"{file_name_without_ext}.ico")
 
        # 调整图像大小为 256x256
        image_256 = image.resize((256, 256), Image.Resampling.LANCZOS)
 
        # 保存为 ICO 文件
        image_256.save(ico_path, format='ICO', sizes=[(256, 256)])
 
        ico_file_name = os.path.basename(ico_path)
        success_msg = f"成功将 {file_name_without_ext} 转换为 {ico_file_name}。"
        result_label.config(text=success_msg)
        # 转换完成后,修改按钮文本并禁用按钮
        convert_button.config(text="转换完成", state=tk.DISABLED)
    except Exception as e:
        file_name = os.path.basename(image_path)
        error_msg = f"错误:{file_name} 可能不是有效的图像文件,错误信息:{e}"
        result_label.config(text=error_msg)
 
 
def select_image_file():
    file_path = filedialog.askopenfilename(filetypes=[("图像文件", "*.png;*.jpg;*.jpeg;*.gif;*.bmp")])
    if file_path:
        file_entry.delete(0, tk.END)
        file_entry.insert(0, file_path)
        # 如果重新选择文件,恢复按钮状态和文本
        convert_button.config(text="开始转换", state=tk.NORMAL)
 
 
def start_conversion():
    image_path = file_entry.get()
    if image_path:
        convert_image_to_ico(image_path)
 
 
# 创建主窗口
root = tk.Tk()
root.title("图像转 256x256 ICO")
# 固定窗体大小
root.geometry("400x250")
root.resizable(False, False)
 
# 创建选择文件按钮
select_button = tk.Button(root, text="选择图像文件", command=select_image_file)
select_button.pack(pady=10)
 
# 创建文件路径输入框
file_entry = tk.Entry(root, width=50)
file_entry.pack(pady=5)
 
# 创建转换按钮
convert_button = tk.Button(root, text="开始转换", command=start_conversion)
convert_button.pack(pady=10)
 
# 创建结果显示标签
result_label = tk.Label(root, text="", wraplength=380# 设置 wraplength 为比窗口宽度略小的值
result_label.pack(pady=10)
 
# 运行主循环
root.mainloop()

免费评分

参与人数 4吾爱币 +8 热心值 +4 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
kingstarg + 1 + 1 谢谢@Thanks!
psqladm + 1 + 1 用心讨论,共获提升!
laozhang4201 + 1 + 1 热心回复!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

一直等下去 发表于 2025-3-7 14:48
本帖最后由 一直等下去 于 2025-3-7 14:53 编辑

在此基础上做了个升级,

具体功能如下:
ICO转换工具版本对比分析报告
| 功能类别 | 旧版本 (ico.py) | 新版本 (new.py) | 改进说明
||---------|----------------|----------------|----------||
基础功能 | | | |
| 图像转ICO | &#10003; 仅支持单一合并模式 | &#10003; 支持合并/分离两种模式 | 新增分别输出各尺寸选项 |
| 支持的图像格式 | PNG, JPG, JPEG, GIF, BMP | PNG, JPG, JPEG, GIF, BMP, TIFF, WebP | 增加了更多格式支持 |
| 界面功能 | | | |
| 主题支持 | &#10007; 无 | &#10003; 支持浅色/深色主题 | 新增主题切换功能 |
| 文件拖放 | &#10007; 无 | &#10003; 支持文件和文件夹拖放 | 提升操作便利性 |
| 预览功能 | &#10003; 基础预览 | &#10003; 增强预览(含详细信息) | 显示更多图像信息 |
| 列表管理 | &#10003; 基础管理 | &#10003; 支持拖动排序和多选 | 增强文件管理能力 |
| 转换功能 | | | |
| 批量转换 | &#10003; 基础支持 | &#10003; 增强支持(含进度显示) | 改进批量处理体验 |
| 尺寸选择 | &#10003; 固定256x256 | &#10003; 多尺寸可选 | 更灵活的尺寸选择 |
| 输出模式 | &#10003; 单一模式 | &#10003; 两种模式可选 | 新增分离输出模式 |
| 用户体验 | | | |
| 进度显示 | &#10007; 无 | &#10003; 进度条显示 | 提供转换进度反馈 |
| 错误处理 | &#10003; 基础提示 | &#10003; 详细错误信息 | 更完善的错误处理 |
| 状态反馈 | &#10003; 简单提示 | &#10003; 详细状态信息 | 提供更多操作反馈 |
| 其他功能 | | | || 配置保存 | &#10007; 无 | &#10003; 支持配置持久化 | 记住用户偏好设置 |
| ICO信息查看 | &#10007; 无 | &#10003; 支持查看ICO详情 | 可查看生成文件信息 |
| 取消转换 | &#10007; 无 | &#10003; 支持取消操作 | 可中断转换过程 |


新版本在保留原有基础功能的同时,全方位提升了程序的功能性和易用性。
代码如下,需要自取:
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
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
import tkinter as tk
from tkinter import filedialog, ttk, messagebox
from PIL import Image, ImageTk
import os
import threading
import json
from tkinter.colorchooser import askcolor
import sys
 
# 支持的图像文件扩展名
SUPPORTED_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')
 
# 配置文件路径
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ico_converter_config.json')
 
# 默认配置
DEFAULT_CONFIG = {
    'last_directory': '',
    'output_directory': '',
    'theme': 'light',
    'icon_sizes': [16, 32, 48, 64, 128, 256]
}
 
# 主题颜色
THEMES = {
    'light': {
        'bg': '#f0f0f0',
        'fg': '#000000',
        'button_bg': '#e0e0e0',
        'button_fg': '#000000',
        'entry_bg': '#ffffff',
        'entry_fg': '#000000',
        'highlight_bg': '#0078d7',
        'highlight_fg': '#ffffff'
    },
    'dark': {
        'bg': '#2d2d2d',
        'fg': '#ffffff',
        'button_bg': '#444444',
        'button_fg': '#ffffff',
        'entry_bg': '#3d3d3d',
        'entry_fg': '#ffffff',
        'highlight_bg': '#0078d7',
        'highlight_fg': '#ffffff'
    }
}
 
class DragDropListbox(tk.Listbox):
    """支持拖放功能的Listbox"""
     
    def __init__(self, master, **kw):
        super().__init__(master, **kw)
        self.bind('<Button-1>', self.select_item)
        self.bind('<B1-Motion>', self.move_item)
        self.curIndex = None
     
    def select_item(self, event):
        self.curIndex = self.nearest(event.y)
     
    def move_item(self, event):
        new_index = self.nearest(event.y)
        if new_index != self.curIndex and 0 <= new_index < self.size():
            item_text = self.get(self.curIndex)
            self.delete(self.curIndex)
            self.insert(new_index, item_text)
            self.curIndex = new_index
            self.selection_set(self.curIndex)
 
class ImageDropTarget:
    """处理文件拖放的类"""
     
    def __init__(self, widget, callback):
        self.widget = widget
        self.callback = callback
         
        # 绑定拖放事件
        try:
            self.widget.drop_target_register('DND_Files')
            self.widget.dnd_bind('<<Drop>>', self.on_drop)
        except:
            # 如果TkinterDnD不可用,则跳过
            pass
     
    def on_drop(self, event):
        # 获取拖放的文件路径
        files = self.widget.tk.splitlist(event.data)
        valid_files = []
         
        for file_path in files:
            if os.path.isfile(file_path) and any(file_path.lower().endswith(ext) for ext in SUPPORTED_EXTENSIONS):
                valid_files.append(file_path)
         
        if valid_files:
            self.callback(valid_files)
 
class IcoConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("增强版图像转ICO工具")
        self.root.geometry("800x600")
        self.root.minsize(800, 600)
         
        # 加载配置
        self.config = self.load_config()
         
        # 设置主题
        self.current_theme = self.config['theme']
        self.apply_theme()
         
        # 创建主框架
        self.main_frame = ttk.Frame(root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
         
        # 创建左右分栏
        self.left_frame = ttk.Frame(self.main_frame)
        self.left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
         
        self.right_frame = ttk.Frame(self.main_frame)
        self.right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=(5, 0))
         
        # 创建文件选择区域
        self.create_file_selection_area()
         
        # 创建预览区域
        self.create_preview_area()
         
        # 创建设置区域
        self.create_settings_area()
         
        # 创建转换按钮和进度条
        self.create_conversion_controls()
         
        # 创建状态栏
        self.create_status_bar()
         
        # 尝试设置拖放支持
        try:
            # 尝试导入TkinterDnD
            self.root.tk.eval('package require tkdnd')
            from tkinterdnd2 import TkinterDnD, DND_FILES
            # 如果成功导入,则设置拖放支持
            self.setup_drag_drop()
        except:
            # 如果导入失败,则显示提示信息
            self.status_var.set("提示:安装 tkinterdnd2 包可启用拖放功能")
         
        # 绑定关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
     
    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(CONFIG_FILE):
                with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                # 确保所有必要的键都存在
                for key, value in DEFAULT_CONFIG.items():
                    if key not in config:
                        config[key] = value
                return config
        except Exception as e:
            print(f"加载配置文件失败: {e}")
        return DEFAULT_CONFIG.copy()
     
    def save_config(self):
        """保存配置文件"""
        try:
            with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
     
    def apply_theme(self):
        """应用主题"""
        theme = THEMES[self.current_theme]
        self.root.configure(bg=theme['bg'])
         
        # 创建自定义样式
        style = ttk.Style()
        style.theme_use('clam'# 使用clam主题作为基础
         
        # 配置TTK样式
        style.configure('TFrame', background=theme['bg'])
        style.configure('TLabel', background=theme['bg'], foreground=theme['fg'])
        style.configure('TButton', background=theme['button_bg'], foreground=theme['button_fg'])
        style.configure('TCheckbutton', background=theme['bg'], foreground=theme['fg'])
        style.configure('TRadiobutton', background=theme['bg'], foreground=theme['fg'])
        style.configure('TEntry', fieldbackground=theme['entry_bg'], foreground=theme['entry_fg'])
        style.configure('TCombobox', fieldbackground=theme['entry_bg'], foreground=theme['entry_fg'])
        style.configure('Horizontal.TProgressbar', background=theme['highlight_bg'])
         
        # 更新配置
        self.config['theme'] = self.current_theme
        self.save_config()
     
    def create_file_selection_area(self):
        """创建文件选择区域"""
        file_frame = ttk.LabelFrame(self.left_frame, text="文件选择")
        file_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 5))
         
        # 文件列表
        list_frame = ttk.Frame(file_frame)
        list_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
         
        self.file_listbox = DragDropListbox(
            list_frame,
            selectmode=tk.EXTENDED,
            bg=THEMES[self.current_theme]['entry_bg'],
            fg=THEMES[self.current_theme]['entry_fg'],
            selectbackground=THEMES[self.current_theme]['highlight_bg'],
            selectforeground=THEMES[self.current_theme]['highlight_fg']
        )
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.file_listbox.yview)
        self.file_listbox.configure(yscrollcommand=scrollbar.set)
         
        self.file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
         
        # 文件操作按钮
        button_frame = ttk.Frame(file_frame)
        button_frame.pack(fill=tk.X, padx=5, pady=5)
         
        add_button = ttk.Button(button_frame, text="添加文件", command=self.add_files)
        add_button.pack(side=tk.LEFT, padx=(0, 5))
         
        add_dir_button = ttk.Button(button_frame, text="添加文件夹", command=self.add_directory)
        add_dir_button.pack(side=tk.LEFT, padx=(0, 5))
         
        remove_button = ttk.Button(button_frame, text="移除选中", command=self.remove_selected_files)
        remove_button.pack(side=tk.LEFT, padx=(0, 5))
         
        clear_button = ttk.Button(button_frame, text="清空列表", command=self.clear_file_list)
        clear_button.pack(side=tk.LEFT)
         
        # 绑定双击事件以预览图像
        self.file_listbox.bind('<Double-1>', self.preview_selected_image)
     
    def create_preview_area(self):
        """创建预览区域"""
        preview_frame = ttk.LabelFrame(self.right_frame, text="图像预览")
        preview_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 5))
         
        self.preview_canvas = tk.Canvas(
            preview_frame,
            bg=THEMES[self.current_theme]['entry_bg'],
            highlightthickness=0
        )
        self.preview_canvas.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
         
        # 预览信息标签
        self.preview_info = ttk.Label(preview_frame, text="双击左侧列表中的图像进行预览")
        self.preview_info.pack(pady=(0, 5))
         
        # 存储预览图像引用
        self.preview_image = None
     
    def create_settings_area(self):
        """创建设置区域"""
        settings_frame = ttk.LabelFrame(self.left_frame, text="转换设置")
        settings_frame.pack(fill=tk.X, pady=(0, 5))
         
        # 图标尺寸选择
        size_frame = ttk.Frame(settings_frame)
        size_frame.pack(fill=tk.X, padx=5, pady=5)
         
        ttk.Label(size_frame, text="图标尺寸:").pack(side=tk.LEFT)
         
        # 创建尺寸选择框架
        sizes_frame = ttk.Frame(size_frame)
        sizes_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 0))
         
        # 创建尺寸复选框
        self.size_vars = {}
        available_sizes = [16, 32, 48, 64, 128, 256]
         
        for i, size in enumerate(available_sizes):
            var = tk.BooleanVar(value=size in self.config['icon_sizes'])
            self.size_vars[size] = var
             
            cb = ttk.Checkbutton(
                sizes_frame,
                text=f"{size}x{size}",
                variable=var,
                command=self.update_size_config
            )
            row, col = divmod(i, 3)
            cb.grid(row=row, column=col, sticky=tk.W, padx=5)
         
        # 添加输出模式选择
        mode_frame = ttk.Frame(settings_frame)
        mode_frame.pack(fill=tk.X, padx=5, pady=5)
         
        ttk.Label(mode_frame, text="输出模式:").pack(side=tk.LEFT)
         
        self.output_mode = tk.StringVar(value="combined")
        ttk.Radiobutton(
            mode_frame,
            text="合并为单个ICO",
            variable=self.output_mode,
            value="combined"
        ).pack(side=tk.LEFT, padx=(5, 10))
         
        ttk.Radiobutton(
            mode_frame,
            text="分别输出各尺寸",
            variable=self.output_mode,
            value="separate"
        ).pack(side=tk.LEFT)
         
        # 输出目录选择
        output_frame = ttk.Frame(settings_frame)
        output_frame.pack(fill=tk.X, padx=5, pady=5)
         
        ttk.Label(output_frame, text="输出目录:").pack(side=tk.LEFT)
         
        self.output_var = tk.StringVar(value=self.config['output_directory'])
        output_entry = ttk.Entry(output_frame, textvariable=self.output_var)
        output_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 5))
         
        output_button = ttk.Button(output_frame, text="浏览...", command=self.select_output_directory)
        output_button.pack(side=tk.LEFT)
         
        # 主题切换
        theme_frame = ttk.Frame(settings_frame)
        theme_frame.pack(fill=tk.X, padx=5, pady=5)
         
        ttk.Label(theme_frame, text="界面主题:").pack(side=tk.LEFT)
         
        self.theme_var = tk.StringVar(value=self.current_theme)
        light_rb = ttk.Radiobutton(
            theme_frame,
            text="浅色",
            variable=self.theme_var,
            value="light",
            command=self.change_theme
        )
        light_rb.pack(side=tk.LEFT, padx=(5, 10))
         
        dark_rb = ttk.Radiobutton(
            theme_frame,
            text="深色",
            variable=self.theme_var,
            value="dark",
            command=self.change_theme
        )
        dark_rb.pack(side=tk.LEFT)
     
    def create_conversion_controls(self):
        """创建转换控制区域"""
        control_frame = ttk.Frame(self.right_frame)
        control_frame.pack(fill=tk.X, pady=(0, 5))
         
        # 转换按钮
        self.convert_button = ttk.Button(
            control_frame,
            text="开始转换",
            command=self.start_conversion
        )
        self.convert_button.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
         
        # 取消按钮
        self.cancel_button = ttk.Button(
            control_frame,
            text="取消",
            state=tk.DISABLED,
            command=self.cancel_conversion
        )
        self.cancel_button.pack(side=tk.LEFT, fill=tk.X, expand=True)
         
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            self.right_frame,
            orient=tk.HORIZONTAL,
            length=100,
            mode='determinate',
            variable=self.progress_var
        )
        self.progress_bar.pack(fill=tk.X, pady=(0, 5))
         
        # 转换标志
        self.converting = False
        self.cancel_requested = False
     
    def create_status_bar(self):
        """创建状态栏"""
        self.status_var = tk.StringVar(value="就绪")
        status_bar = ttk.Label(
            self.root,
            textvariable=self.status_var,
            relief=tk.SUNKEN,
            anchor=tk.W
        )
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)
     
    def setup_drag_drop(self):
        """设置拖放支持"""
        try:
            from tkinterdnd2 import DND_FILES
            self.root.drop_target_register(DND_FILES)
            self.root.dnd_bind('<<Drop>>', self.on_drop_files)
             
            self.file_listbox.drop_target_register(DND_FILES)
            self.file_listbox.dnd_bind('<<Drop>>', self.on_drop_files)
             
            self.preview_canvas.drop_target_register(DND_FILES)
            self.preview_canvas.dnd_bind('<<Drop>>', self.on_drop_files)
             
            self.status_var.set("拖放功能已启用")
        except Exception as e:
            print(f"设置拖放支持失败: {e}")
     
    def on_drop_files(self, event):
        """处理文件拖放事件"""
        files = self.root.tk.splitlist(event.data)
        self.process_dropped_files(files)
     
    def process_dropped_files(self, files):
        """处理拖放的文件"""
        image_files = []
         
        for file_path in files:
            if os.path.isdir(file_path):
                # 如果是目录,则添加目录中的所有图像文件
                for root, _, filenames in os.walk(file_path):
                    for filename in filenames:
                        full_path = os.path.join(root, filename)
                        if any(filename.lower().endswith(ext) for ext in SUPPORTED_EXTENSIONS):
                            image_files.append(full_path)
            elif os.path.isfile(file_path) and any(file_path.lower().endswith(ext) for ext in SUPPORTED_EXTENSIONS):
                # 如果是支持的图像文件,则添加到列表
                image_files.append(file_path)
         
        if image_files:
            # 添加到文件列表
            for file_path in image_files:
                if file_path not in self.get_file_list():
                    self.file_listbox.insert(tk.END, file_path)
             
            # 更新状态
            self.status_var.set(f"已添加 {len(image_files)} 个文件")
             
            # 如果只添加了一个文件,则预览它
            if len(image_files) == 1:
                self.preview_image_file(image_files[0])
     
    def add_files(self):
        """添加文件"""
        initial_dir = self.config['last_directory'] if self.config['last_directory'] else os.path.expanduser("~")
         
        files = filedialog.askopenfilenames(
            title="选择图像文件",
            initialdir=initial_dir,
            filetypes=[
                ("所有支持的图像", " ".join(f"*{ext}" for ext in SUPPORTED_EXTENSIONS)),
                ("PNG 文件", "*.png"),
                ("JPEG 文件", "*.jpg *.jpeg"),
                ("GIF 文件", "*.gif"),
                ("BMP 文件", "*.bmp"),
                ("TIFF 文件", "*.tiff *.tif"),
                ("WebP 文件", "*.webp"),
                ("所有文件", "*.*")
            ]
        )
         
        if files:
            # 更新最后访问的目录
            self.config['last_directory'] = os.path.dirname(files[0])
            self.save_config()
             
            # 添加到文件列表
            for file_path in files:
                if file_path not in self.get_file_list():
                    self.file_listbox.insert(tk.END, file_path)
             
            # 更新状态
            self.status_var.set(f"已添加 {len(files)} 个文件")
             
            # 如果只添加了一个文件,则预览它
            if len(files) == 1:
                self.preview_image_file(files[0])
     
    def add_directory(self):
        """添加目录中的所有图像文件"""
        initial_dir = self.config['last_directory'] if self.config['last_directory'] else os.path.expanduser("~")
         
        directory = filedialog.askdirectory(
            title="选择包含图像的文件夹",
            initialdir=initial_dir
        )
         
        if directory:
            # 更新最后访问的目录
            self.config['last_directory'] = directory
            self.save_config()
             
            # 添加目录中的所有图像文件
            image_files = []
            for root, _, filenames in os.walk(directory):
                for filename in filenames:
                    if any(filename.lower().endswith(ext) for ext in SUPPORTED_EXTENSIONS):
                        full_path = os.path.join(root, filename)
                        image_files.append(full_path)
             
            # 添加到文件列表
            for file_path in image_files:
                if file_path not in self.get_file_list():
                    self.file_listbox.insert(tk.END, file_path)
             
            # 更新状态
            self.status_var.set(f"已从目录添加 {len(image_files)} 个文件")
     
    def remove_selected_files(self):
        """移除选中的文件"""
        selected_indices = self.file_listbox.curselection()
         
        if not selected_indices:
            return
         
        # 从后往前删除,避免索引变化
        for index in sorted(selected_indices, reverse=True):
            self.file_listbox.delete(index)
         
        # 更新状态
        self.status_var.set(f"已移除 {len(selected_indices)} 个文件")
         
        # 清除预览
        self.clear_preview()
     
    def clear_file_list(self):
        """清空文件列表"""
        if self.file_listbox.size() > 0:
            self.file_listbox.delete(0, tk.END)
            self.status_var.set("已清空文件列表")
            self.clear_preview()
     
    def get_file_list(self):
        """获取文件列表中的所有文件路径"""
        return [self.file_listbox.get(i) for i in range(self.file_listbox.size())]
     
    def preview_selected_image(self, event=None):
        """预览选中的图像"""
        selected_indices = self.file_listbox.curselection()
         
        if not selected_indices:
            return
         
        # 获取选中的文件路径
        file_path = self.file_listbox.get(selected_indices[0])
        self.preview_image_file(file_path)
     
    def preview_image_file(self, file_path):
        """预览图像文件"""
        try:
            # 打开图像
            image = Image.open(file_path)
             
            # 获取图像信息
            width, height = image.size
            format_name = image.format
            mode = image.mode
             
            # 调整图像大小以适应预览区域
            canvas_width = self.preview_canvas.winfo_width()
            canvas_height = self.preview_canvas.winfo_height()
             
            # 如果画布尚未调整大小,则使用默认值
            if canvas_width <= 1:
                canvas_width = 300
            if canvas_height <= 1:
                canvas_height = 300
             
            # 计算缩放比例
            scale = min(canvas_width / width, canvas_height / height)
            new_width = int(width * scale)
            new_height = int(height * scale)
             
            # 调整图像大小
            resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
             
            # 转换为PhotoImage
            photo = ImageTk.PhotoImage(resized_image)
             
            # 清除画布
            self.preview_canvas.delete("all")
             
            # 显示图像
            self.preview_canvas.create_image(
                canvas_width // 2,
                canvas_height // 2,
                image=photo,
                anchor=tk.CENTER
            )
             
            # 保存引用
            self.preview_image = photo
             
            # 更新信息标签
            file_name = os.path.basename(file_path)
            info_text = f"{file_name} ({width}x{height}, {format_name}, {mode})"
            self.preview_info.config(text=info_text)
             
            # 更新状态
            self.status_var.set(f"预览: {file_name}")
        except Exception as e:
            self.clear_preview()
            self.preview_info.config(text=f"无法预览: {os.path.basename(file_path)}")
            self.status_var.set(f"预览失败: {e}")
     
    def clear_preview(self):
        """清除预览"""
        self.preview_canvas.delete("all")
        self.preview_info.config(text="双击左侧列表中的图像进行预览")
        self.preview_image = None
     
    def select_output_directory(self):
        """选择输出目录"""
        initial_dir = self.config['output_directory'] if self.config['output_directory'] else os.path.expanduser("~")
         
        directory = filedialog.askdirectory(
            title="选择输出目录",
            initialdir=initial_dir
        )
         
        if directory:
            self.output_var.set(directory)
            self.config['output_directory'] = directory
            self.save_config()
            self.status_var.set(f"已设置输出目录: {directory}")
     
    def update_size_config(self):
        """更新尺寸配置"""
        selected_sizes = [size for size, var in self.size_vars.items() if var.get()]
         
        if not selected_sizes:
            # 如果没有选择任何尺寸,则默认选择256x256
            self.size_vars[256].set(True)
            selected_sizes = [256]
         
        self.config['icon_sizes'] = selected_sizes
        self.save_config()
     
    def change_theme(self):
        """切换主题"""
        self.current_theme = self.theme_var.get()
        self.apply_theme()
         
        # 更新列表框颜色
        self.file_listbox.config(
            bg=THEMES[self.current_theme]['entry_bg'],
            fg=THEMES[self.current_theme]['entry_fg'],
            selectbackground=THEMES[self.current_theme]['highlight_bg'],
            selectforeground=THEMES[self.current_theme]['highlight_fg']
        )
         
        # 更新画布颜色
        self.preview_canvas.config(
            bg=THEMES[self.current_theme]['entry_bg']
        )
         
        # 重新预览当前图像
        selected_indices = self.file_listbox.curselection()
        if selected_indices:
            self.preview_selected_image()
         
        self.status_var.set(f"已切换到{self.current_theme}主题")
     
    def start_conversion(self):
        """开始转换"""
        # 获取文件列表
        file_list = self.get_file_list()
         
        if not file_list:
            messagebox.showinfo("提示", "请先添加图像文件")
            return
         
        # 获取选中的尺寸
        selected_sizes = [size for size, var in self.size_vars.items() if var.get()]
         
        if not selected_sizes:
            messagebox.showinfo("提示", "请至少选择一个图标尺寸")
            return
         
        # 获取输出目录
        output_dir = self.output_var.get()
         
        # 如果未指定输出目录,则使用第一个文件的目录
        if not output_dir:
            output_dir = os.path.dirname(file_list[0])
            self.output_var.set(output_dir)
         
        # 检查输出目录是否存在
        if not os.path.exists(output_dir):
            try:
                os.makedirs(output_dir)
            except Exception as e:
                messagebox.showerror("错误", f"无法创建输出目录: {e}")
                return
         
        # 禁用控件
        self.convert_button.config(state=tk.DISABLED)
        self.cancel_button.config(state=tk.NORMAL)
        self.file_listbox.config(state=tk.DISABLED)
         
        # 重置进度条
        self.progress_var.set(0)
         
        # 设置转换标志
        self.converting = True
        self.cancel_requested = False
         
        # 启动转换线程
        self.conversion_thread = threading.Thread(
            target=self.convert_images,
            args=(file_list, selected_sizes, output_dir)
        )
        self.conversion_thread.daemon = True
        self.conversion_thread.start()
         
        # 启动进度更新
        self.root.after(100, self.update_conversion_progress)
 
    def convert_images(self, file_list, sizes, output_dir):
        """在后台线程中转换图像"""
        total_files = len(file_list)
        processed_files = 0
        successful_files = 0
        failed_files = []
         
        for file_path in file_list:
            if self.cancel_requested:
                break
             
            try:
                # 更新状态
                file_name = os.path.basename(file_path)
                self.update_status(f"正在转换: {file_name}")
                 
                # 检查文件是否存在
                if not os.path.exists(file_path):
                    failed_files.append((file_path, "文件不存在"))
                    continue
                 
                # 检查文件扩展名
                if not any(file_path.lower().endswith(ext) for ext in SUPPORTED_EXTENSIONS):
                    failed_files.append((file_path, "不支持的文件格式"))
                    continue
                 
                # 打开图像
                image = Image.open(file_path)
                 
                # 获取文件名(不包含扩展名)
                file_name_without_ext = os.path.splitext(os.path.basename(file_path))[0]
                 
                # 准备不同尺寸的图像
                images = []
                for size in sorted(sizes, reverse=True):
                    resized_image = image.resize((size, size), Image.Resampling.LANCZOS)
                    images.append(resized_image)
                 
                # 根据输出模式保存文件
                if self.output_mode.get() == "combined":
                    # 合并为单个ICO文件
                    ico_path = os.path.join(output_dir, f"{file_name_without_ext}.ico")
                    images[0].save(
                        ico_path,
                        format='ICO',
                        sizes=[(size, size) for size in sorted(sizes, reverse=True)],
                        append_images=images[1:] if len(images) > 1 else [],
                        bitmap_format='bmp'
                    )
                else:
                    # 分别输出各尺寸
                    for size, img in zip(sorted(sizes, reverse=True), images):
                        ico_path = os.path.join(output_dir, f"{file_name_without_ext}_{size}x{size}.ico")
                        img.save(
                            ico_path,
                            format='ICO',
                            sizes=[(size, size)],
                            bitmap_format='bmp'
                        )
                 
                successful_files += 1
            except Exception as e:
                failed_files.append((file_path, str(e)))
             
            processed_files += 1
            self.update_progress(processed_files / total_files)
         
        # 更新最终状态
        if self.cancel_requested:
            self.update_status("转换已取消")
        elif failed_files:
            self.update_status(f"转换完成: {successful_files} 成功, {len(failed_files)} 失败")
            self.show_conversion_results(successful_files, failed_files, file_list, output_dir)
        else:
            self.update_status(f"转换完成: 所有 {successful_files} 个文件转换成功")
            self.show_conversion_results(successful_files, [], file_list, output_dir)
         
        # 重置转换标志
        self.converting = False
 
    def update_conversion_progress(self):
        """更新转换进度"""
        if self.converting:
            # 继续更新
            self.root.after(100, self.update_conversion_progress)
        else:
            # 转换完成,恢复控件状态
            self.convert_button.config(state=tk.NORMAL)
            self.cancel_button.config(state=tk.DISABLED)
            self.file_listbox.config(state=tk.NORMAL)
 
    def update_progress(self, progress):
        """更新进度条"""
        self.progress_var.set(progress * 100)
 
    def update_status(self, status):
        """更新状态栏"""
        self.status_var.set(status)
 
    def cancel_conversion(self):
        """取消转换"""
        if self.converting:
            self.cancel_requested = True
            self.status_var.set("正在取消转换...")
            self.cancel_button.config(state=tk.DISABLED)
 
    def show_conversion_results(self, successful_count, failed_files, file_list=None, output_dir=None):
        """显示转换结果"""
        if not failed_files:
            messagebox.showinfo("转换完成", f"所有 {successful_count} 个文件转换成功!")
            # 如果只有一个文件,显示其ICO信息
            if successful_count == 1 and file_list and output_dir:
                ico_path = os.path.join(output_dir, f"{os.path.splitext(os.path.basename(file_list[0]))[0]}.ico")
                self.show_ico_info(ico_path)
            return
         
        # 创建结果对话框
        result_dialog = tk.Toplevel(self.root)
        result_dialog.title("转换结果")
        result_dialog.geometry("500x300")
        result_dialog.transient(self.root)
        result_dialog.grab_set()
         
        # 设置对话框主题
        result_dialog.configure(bg=THEMES[self.current_theme]['bg'])
         
        # 创建标签
        header_label = tk.Label(
            result_dialog,
            text=f"转换完成: {successful_count} 成功, {len(failed_files)} 失败",
            bg=THEMES[self.current_theme]['bg'],
            fg=THEMES[self.current_theme]['fg'],
            font=("", 12, "bold")
        )
        header_label.pack(pady=(10, 5))
         
        # 创建失败文件列表
        frame = tk.Frame(
            result_dialog,
            bg=THEMES[self.current_theme]['bg']
        )
        frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
         
        # 创建滚动条
        scrollbar = tk.Scrollbar(frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
         
        # 创建文本框
        text = tk.Text(
            frame,
            wrap=tk.WORD,
            yscrollcommand=scrollbar.set,
            bg=THEMES[self.current_theme]['entry_bg'],
            fg=THEMES[self.current_theme]['entry_fg'],
            height=10
        )
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
         
        scrollbar.config(command=text.yview)
         
        # 添加失败文件信息
        for file_path, error in failed_files:
            file_name = os.path.basename(file_path)
            text.insert(tk.END, f"{file_name}: {error}\n")
         
        text.config(state=tk.DISABLED)
         
        # 创建关闭按钮
        close_button = tk.Button(
            result_dialog,
            text="关闭",
            command=result_dialog.destroy,
            bg=THEMES[self.current_theme]['button_bg'],
            fg=THEMES[self.current_theme]['button_fg']
        )
        close_button.pack(pady=(5, 10))
 
    def on_close(self):
        """关闭应用程序"""
        if self.converting:
            if messagebox.askyesno("确认", "正在进行转换,确定要退出吗?"):
                self.cancel_requested = True
                self.root.after(500, self.root.destroy)
        else:
            self.save_config()
            self.root.destroy()
 
    def show_ico_info(self, ico_path):
        """显示ICO文件中包含的所有尺寸"""
        try:
            with Image.open(ico_path) as img:
                sizes = []
                 
                # 首先尝试从图像信息中获取尺寸列表
                if 'sizes' in img.info:
                    sizes = [f"{w}x{h}" for w, h in img.info['sizes']]
                else:
                    # 如果info中没有sizes信息,则遍历所有图像
                    current = 0
                    while True:
                        try:
                            img.seek(current)
                            sizes.append(f"{img.width}x{img.height}")
                            current += 1
                        except EOFError:
                            break
                 
                # 如果还是没有获取到尺寸信息,至少显示当前尺寸
                if not sizes:
                    sizes = [f"{img.width}x{img.height}"]
                 
                # 对尺寸进行排序(从小到大)
                sizes.sort(key=lambda x: int(x.split('x')[0]))
                 
                # 显示尺寸信息
                size_info = "、".join(sizes)
                messagebox.showinfo("ICO文件信息",
                                  f"文件: {os.path.basename(ico_path)}\n"
                                  f"包含的尺寸: {size_info}")
                 
                # 打印调试信息
                print(f"ICO文件信息:")
                print(f"sizes in info: {img.info.get('sizes', 'Not found')}")
                print(f"detected sizes: {sizes}")
                 
        except Exception as e:
            messagebox.showerror("错误", f"无法读取ICO文件信息: {e}")
            print(f"Error reading ICO file: {e}")
 
def main():
    # 尝试导入tkinterdnd2
    try:
        from tkinterdnd2 import TkinterDnD
        root = TkinterDnD.Tk()
    except ImportError:
        root = tk.Tk()
     
    app = IcoConverterApp(root)
    root.mainloop()
 
if __name__ == "__main__":
    main()

新界面

新界面
IdeaM 发表于 2025-3-6 00:09
现在AI真的很厉害,简单的安装一个VSCODE,然后加个扩展mars code AI,轻松用网页实现很多功能。
52PJ070 发表于 2025-3-6 00:52
这个软件功能很实用很方便,感谢提供分享!
hxf1632 发表于 2025-3-6 08:22
制作软件图标很方便,很好。
hnwang 发表于 2025-3-6 08:46
感谢分享。。很方便
94e8v061 发表于 2025-3-6 08:59
大家的ai都出成果了。
shenlrq 发表于 2025-3-6 09:01
应该挺好玩的,谢谢分享
lyue0771 发表于 2025-3-6 09:19
好的,谢谢分享
sdieedu 发表于 2025-3-6 09:22
感谢分享啊
mqt4453 发表于 2025-3-6 09:40
谢谢分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-4-26 07:09

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表