from PIL import Image

def split_image(image_path, output_dir, icon_dim=(3, 3)):
    try:
        # 元画像を開く
        img = Image.open(image_path)
        img_width, img_height = img.size
        
        # 分割処理
        icon_size = [0, 0]
        icon_size[0] = img_width // icon_dim[0]
        icon_size[1] = img_height // icon_dim[1]
        num_cols = icon_dim[0]
        num_rows = icon_dim[1]
        
        for row in range(num_rows):
            for col in range(num_cols):
                # アイコンの切り取り範囲
                left = col * icon_size[0]
                upper = row * icon_size[1]
                right = left + icon_size[0]
                lower = upper + icon_size[1]
                
                # 切り取って保存
                icon = img.crop((left, upper, right, lower))
                icon.save(f"{output_dir}/icon_{row}_{col}.png")
        
        print(f"アイコンを {output_dir} に保存しました！")
    except Exception as e:
        print(f"エラー: {e}")

# 使用例
split_image("icons.png", ".")
