Python学习2,拆分plist图集,还原成小图

Python学习2,拆分plist图集,还原成小图

python的库太强大了,我们搬搬砖就ok了

运行环境:安装python,安装第三方库Pillow,biplist
Pillow用来操作图片,biplist解析plist文件

即用链接:下载地址(Win) 下载地址(Mac)
Mac下请使用命令(chmod +x UnpackTP_Mac)将文件变为可执行文件

import os
import re
from biplist import readPlist
from PIL import Image


def split_plist_atlas(path):
    image = Image.open(os.path.splitext(path)[0]+".png")
    plist = readPlist(os.path.splitext(path)[0]+".plist")
    prefix = os.path.dirname(path)+os.sep + "Sprites_" + \
        get_file_name(path) + os.sep
    frames: dict = plist["frames"]
    regex = re.compile("({|})")
    for k in frames:
        filename = prefix + k.replace("jpg", "png")
        rectKey = "frame" if "frame" in frames[k] else "textureRect"
        rect = regex.sub("", frames[k][rectKey]).split(",")
        rect = [int(v) for v in rect]
        rotateKey = "rotated" if "rotated" in frames[k] else "textureRotated"
        rotate: bool = frames[k][rotateKey]
        x = rect[0]
        y = rect[1]
        w = rect[0] + rect[2] if not rotate else rect[0] + rect[3]
        h = rect[1] + rect[3] if not rotate else rect[1] + rect[2]
        box = (x, y, w, h)
        img = image.crop(box)
        if not os.path.exists(prefix):
            os.makedirs(prefix)
        if rotate:
            img = img.rotate(90, expand=1)
        img.save(filename)
        print(filename)


def get_file_name(path):
    filename: str = os.path.split(path)[-1]
    index = filename.rfind(".")
    return filename[0:index]


while True:
    path = input("请将图片资源或plist文件拖到此处:").strip()
    print()
    if os.path.exists(path):
        if os.path.exists(os.path.splitext(path)[0]+".plist"):
            try:
                split_plist_atlas(path)
                print("\nOver\n")
            except Exception as e:
                print("Exception ", e, "\n")
                print("文件解析出错,请重试\n")
        else:
            print("图片资源或plist文件未找到\n")
    else:
        print("\n文件路径异常,请重试\n")




注意:jpg合成的图集,会强制拆分为png

你可能感兴趣的:(python,plist)