安装最上面的几个库就行,大部分python应该都有

import os
import json
from PIL import Image
import sys

# 确保Python使用UTF-8编码
sys.stdout.reconfigure(encoding='utf-8')

def parse_atlas(atlas_path):
    # 读取Atlas文件,确保使用UTF-8编码
    with open(atlas_path, 'r', encoding='utf-8') as f:
        atlas_data = json.load(f)
    
    # 提取子图片信息
    sub_images = []
    for image_name, attributes in atlas_data["frames"].items():
        frame = attributes["frame"]
        sub_images.append({
            'name': image_name,
            'x': frame['x'],
            'y': frame['y'],
            'width': frame['w'],
            'height': frame['h']
        })

    # 打印调试信息,支持中文输出
    print(f"解析了 {len(sub_images)} 张子图片")
    return sub_images

def extract_images(image_path, sub_images, output_dir):
    try:
        # 打开图集图像
        img = Image.open(image_path)
    except Exception as e:
        print(f"无法打开图片: {e}")
        return

    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)

    # 提取每个子图片并保存
    for sub_image in sub_images:
        # 获取子图片的区域
        box = (
            sub_image['x'],
            sub_image['y'],
            sub_image['x'] + sub_image['width'],
            sub_image['y'] + sub_image['height']
        )
        # 从图集中裁剪出子图片
        cropped_img = img.crop(box)

        # 保存裁剪的子图片,确保保存时路径和文件名支持中文
        save_path = os.path.join(output_dir, sub_image['name'])
        cropped_img.save(save_path)
        print(f"保存了 {save_path}")

def main():
    atlas_file = './main.atlas'  # 替换为你的Atlas文件路径
    image_file = './main.png'  # 替换为你的图集图像路径
    output_directory = './'     # 输出目录

    # 解析Atlas文件
    sub_images = parse_atlas(atlas_file)

    # 提取并保存子图片
    extract_images(image_file, sub_images, output_directory)

if __name__ == '__main__':
    main()