96 lines
3.5 KiB
Python
96 lines
3.5 KiB
Python
import os
|
|
import tkinter as tk
|
|
from tkinter import filedialog, messagebox
|
|
from PIL import Image
|
|
|
|
class ImageConverterApp:
|
|
def __init__(self, root):
|
|
self.root = root
|
|
self.root.title("图标格式转换工具")
|
|
self.root.geometry("500x250")
|
|
|
|
# 存储选中的文件路径
|
|
self.file_path = ""
|
|
|
|
# UI 布局
|
|
self.setup_ui()
|
|
|
|
def setup_ui(self):
|
|
# 标题
|
|
label_title = tk.Label(self.root, text="图片转 ICNS/ICO/PNG 工具", font=("Arial", 14, "bold"))
|
|
label_title.pack(pady=20)
|
|
|
|
# 文件选择部分
|
|
frame_file = tk.Frame(self.root)
|
|
frame_file.pack(pady=10)
|
|
|
|
self.entry_path = tk.Entry(frame_file, width=40)
|
|
self.entry_path.pack(side=tk.LEFT, padx=5)
|
|
|
|
btn_browse = tk.Button(frame_file, text="选择图片", command=self.browse_file)
|
|
btn_browse.pack(side=tk.LEFT)
|
|
|
|
# 开始转换按钮
|
|
self.btn_convert = tk.Button(self.root, text="立即开始转换", command=self.convert_image,
|
|
bg="#4CAF50", fg="white", font=("Arial", 10, "bold"), height=2, width=20)
|
|
self.btn_convert.pack(pady=20)
|
|
|
|
def browse_file(self):
|
|
file_types = [("Image files", "*.jpg *.jpeg *.png *.bmp *.webp")]
|
|
filename = filedialog.askopenfilename(title="选择一张图片", filetypes=file_types)
|
|
if filename:
|
|
self.file_path = filename
|
|
self.entry_path.delete(0, tk.END)
|
|
self.entry_path.insert(0, filename)
|
|
|
|
def convert_image(self):
|
|
if not self.file_path:
|
|
messagebox.showwarning("提示", "请先选择一张图片!")
|
|
return
|
|
|
|
input_path = self.file_path
|
|
base_name = os.path.splitext(os.path.basename(input_path))[0]
|
|
output_dir = os.path.dirname(input_path)
|
|
|
|
try:
|
|
with Image.open(input_path) as img:
|
|
# 1. 裁剪为 1:1
|
|
width, height = img.size
|
|
if width != height:
|
|
new_side = min(width, height)
|
|
left = (width - new_side) / 2
|
|
top = (height - new_side) / 2
|
|
right = (width + new_side) / 2
|
|
bottom = (height + new_side) / 2
|
|
img = img.crop((left, top, right, bottom))
|
|
|
|
# 统一转为 RGBA
|
|
if img.mode != 'RGBA':
|
|
img = img.convert('RGBA')
|
|
|
|
# 2. 保存 512x512 PNG
|
|
png_path = os.path.join(output_dir, f"{base_name}_512.png")
|
|
img.resize((512, 512), Image.Resampling.LANCZOS).save(png_path, "PNG")
|
|
|
|
# 3. 保存 ICNS
|
|
icns_path = os.path.join(output_dir, f"{base_name}.icns")
|
|
img.save(icns_path, format="ICNS")
|
|
|
|
# 4. 保存 256x256 ICO
|
|
ico_256_path = os.path.join(output_dir, f"{base_name}_256.ico")
|
|
img.resize((256, 256), Image.Resampling.LANCZOS).save(ico_256_path, format="ICO", sizes=[(256, 256)])
|
|
|
|
# 5. 保存 32x32 ICO
|
|
ico_32_path = os.path.join(output_dir, f"{base_name}_32.ico")
|
|
img.resize((32, 32), Image.Resampling.LANCZOS).save(ico_32_path, format="ICO", sizes=[(32, 32)])
|
|
|
|
messagebox.showinfo("成功", f"处理完成!\n文件已保存至:\n{output_dir}")
|
|
|
|
except Exception as e:
|
|
messagebox.showerror("错误", f"处理失败: {str(e)}")
|
|
|
|
if __name__ == "__main__":
|
|
root = tk.Tk()
|
|
app = ImageConverterApp(root)
|
|
root.mainloop()
|