import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image

def select_files():
    # 変換元の画像ファイル（PNG, JPEG, BMP）を選択
    file_paths = filedialog.askopenfilenames(
        title="変換する画像を選択（複数選択可）",
        filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")]
    )
    if file_paths:
        listbox.delete(0, tk.END)
        for path in file_paths:
            listbox.insert(tk.END, path)

def convert_images():
    # リストボックスからファイル一覧を取得
    files = listbox.get(0, tk.END)
    if not files:
        messagebox.showwarning("警告", "画像ファイルが選択されていません。")
        return

    # 変換先の拡張子を取得
    target_ext = var_ext.get()

    # 保存先フォルダの選択
    output_dir = filedialog.askdirectory(title="保存先フォルダを選択")
    if not output_dir:
        return

    success_count = 0
    for file_path in files:
        try:
            with Image.open(file_path) as img:
                # 変換元のファイル名（拡張子なし）を取得
                base_name = os.path.splitext(os.path.basename(file_path))[0]
                # 新しいファイルパスを作成
                save_path = os.path.join(output_dir, f"{base_name}.{target_ext}")

                # 変換先がJPEG（jpg/jpeg）の場合の画質維持処理
                if target_ext in ["jpg", "jpeg"]:
                    # 透過情報（RGBAなど）がある場合は白背景（RGB）に統合
                    if img.mode in ("RGBA", "LA"):
                        background = Image.new("RGB", img.size, (255, 255, 255))
                        background.paste(img, mask=img.split()[3] if img.mode == "RGBA" else img.split()[1])
                        # quality=100で最高画質、subsampling=0で色間引きを無効化
                        background.save(save_path, "JPEG", quality=100, subsampling=0)
                    else:
                        # 元から透過がない場合も最高画質で保存
                        img.save(save_path, "JPEG", quality=100, subsampling=0)
                else:
                    # PNGやBMPは標準で劣化しないためそのまま保存
                    img.save(save_path)

                success_count += 1
        except Exception as e:
            print(f"エラー ({os.path.basename(file_path)}): {e}")

    messagebox.showinfo("完了", f"{success_count}個の画像の変換が完了しました！")

# メインウィンドウの設定
root = tk.Tk()
root.title("最高画質・画像フォーマット相互変換ツール")
root.geometry("500x400")

# ① ファイル選択ボタン
btn_select = tk.Button(root, text="① 画像ファイルを選択", command=select_files, bg="#e1e1e1")
btn_select.pack(pady=10)

# ファイル表示リストボックス
listbox = tk.Listbox(root, width=60, height=10)
listbox.pack(pady=5)

# ② 変換先フォーマット選択
frame_ext = tk.Frame(root)
frame_ext.pack(pady=10)

tk.Label(frame_ext, text="② 変換先のフォーマット:").pack(side=tk.LEFT, padx=5)
var_ext = tk.StringVar(value="png")
tk.Radiobutton(frame_ext, text="PNG", variable=var_ext, value="png").pack(side=tk.LEFT)
tk.Radiobutton(frame_ext, text="JPEG", variable=var_ext, value="jpg").pack(side=tk.LEFT)
tk.Radiobutton(frame_ext, text="BMP", variable=var_ext, value="bmp").pack(side=tk.LEFT)

# ③ 変換実行ボタン
btn_convert = tk.Button(root, text="③ 変換して保存", command=convert_images, bg="#4CAF50", fg="white", font=("Arial", 10, "bold"))
btn_convert.pack(pady=10)

root.mainloop()
