【python】plist图集拆分

这篇博客介绍了三种方法来拆分合图,包括通过cocoscreator和cocosstudio的插件工具,以及利用Python的PIL模块手动拆分。重点讲述了使用Python的方法,详细解释了安装PIL、读取plist文件和图片、解析数据并拆分图片的步骤,适合对编程有一定基础的读者进行图像处理。
部署运行你感兴趣的模型镜像

1.使用cocos creator的可以到官方商店找对应的插件工具,不过不是免费的... :( ,链接地址:cocos creator合图拆分

2.使用cocos studio就简单一些,直接新建工程导入plist文件,进入文件所在文件夹,看到一个隐藏文件夹,进入里面就是想要的东西了。参考链接:cocos studio合图拆分

3.就是使用python的PIL图片处理模块来拆分了:

(1)安装python,这个自行百度吧,方法简单。

(2)安装python的PIL模块:

pip install Pillow

(3)代码部分:

          split.py

#!python  
import os,sys  
from xml.etree import ElementTree  
from PIL import Image  
  
def tree_to_dict(tree):  
    d = {}  
    for index, item in enumerate(tree):  
        if item.tag == 'key':  
            if tree[index+1].tag == 'string':  
                d[item.text] = tree[index + 1].text  
            elif tree[index + 1].tag == 'true':  
                d[item.text] = True  
            elif tree[index + 1].tag == 'false':  
                d[item.text] = False  
            elif tree[index+1].tag == 'dict':  
                d[item.text] = tree_to_dict(tree[index+1])  
    return d  
  
def gen_png_from_plist(plist_filename, png_filename):  
    file_path = plist_filename.replace('.plist', '')  
    big_image = Image.open(png_filename)  
    root = ElementTree.fromstring(open(plist_filename, 'r').read())  
    plist_dict = tree_to_dict(root[0])  
    to_list = lambda x: x.replace('{','').replace('}','').split(',')  
    for k,v in plist_dict['frames'].items():  
        rectlist = to_list(v['frame'])  
        width = int( rectlist[3] if v['rotated'] else rectlist[2] )  
        height = int( rectlist[2] if v['rotated'] else rectlist[3] )  
        box=(   
            int(rectlist[0]),  
            int(rectlist[1]),  
            int(rectlist[0]) + width,  
            int(rectlist[1]) + height,  
            )  
        sizelist = [ int(x) for x in to_list(v['sourceSize'])]  
        rect_on_big = big_image.crop(box)  
  
        if v['rotated']:  
            rect_on_big = rect_on_big.rotate(90)  
  
        result_image = Image.new('RGBA', sizelist, (0,0,0,0))  
        #if v['rotated']:  
        #    result_box=(  
        #        ( sizelist[0] - height )//2,  
        #        ( sizelist[1] - width )//2,  
        #        ( sizelist[0] + height )//2,  
        #        ( sizelist[1] + width )//2  
        #        )  
        #else:  
        result_box=(  
            ( sizelist[0] - width )//2,  
            ( sizelist[1] - height )//2,  
            ( sizelist[0] + width )//2,  
            ( sizelist[1] + height )//2  
            )  
        print(rect_on_big, result_box)
        result_image.paste(rect_on_big, result_box, mask=0)  
  
        if not os.path.isdir(file_path):  
            os.mkdir(file_path)  
        outfile = (file_path+'/' + k).replace('gift_', '')  
        print(outfile, "generated")
        result_image.save(outfile)  
  
if __name__ == '__main__':  
    filename = sys.argv[1]  
    plist_filename = filename + '.plist'  
    png_filename = filename + '.png'  
    if (os.path.exists(plist_filename) and os.path.exists(png_filename)):  
        gen_png_from_plist( plist_filename, png_filename )  
    else:  
        print("make sure you have boith plist and png files in the same directory")

(4)将需要拆分的plist文件和图片跟脚本放在同一目录下

 (5)运行拆分脚本:

python split.py block

即可在当前目录下生成一个文件夹,里面包含了所有plist里的图片

 

您可能感兴趣的与本文相关的镜像

GPT-oss:20b

GPT-oss:20b

图文对话
Gpt-oss

GPT OSS 是OpenAI 推出的重量级开放模型,面向强推理、智能体任务以及多样化开发场景

### Mac OS 下的 Plist 图集拆分工具 对于在 macOS 上进行 plist 文件图集拆分的需求,存在多种解决方案。一种常见的方法是通过命令行工具来实现这一功能。 #### 使用 TexturePacker 进行 Plist 图集拆分 TexturePacker 是一款强大的纹理打包和解包工具,不仅适用于 Windows 平台,在 macOS 上也有良好的支持[^1]。该工具提供了图形界面以及命令行接口,能够帮助开发者轻松完成 plist 文件中的图片资源提取工作。除了基本的功能外,还具备高级特性如自动布局优化、重复检测等,有助于提高工作效率并减少手动操作带来的错误风险。 #### 利用 Python 脚本自动化处理 PNG 和 Plist 文件 如果倾向于编程方式解决问题,则可以考虑编写简单的 Python 脚本来读取 `.plist` 文件,并根据其中定义的信息切割对应的 `.png` 图像文件。这种方法灵活性较高,可以根据具体需求定制化调整逻辑流程[^3]。下面是一个基础版本的例子: ```python import os from xml.etree.ElementTree import parse as et_parse try: from PIL import Image, ImageDraw except ImportError: raise Exception('Please install Pillow library first.') def split_atlas(image_path, plist_path, output_dir='.'): tree = et_parse(plist_path).getroot() frames_dict = {} for frame in tree.findall('.//dict')[0].findall('./string|real|integer'): key = frame.tag.lower().strip()[:-len('_filename')] value = float(frame.text.strip()) if 'real'==frame.tag or 'integer'==frame.tag else frame.text.strip() if '_rect' not in key and ('_offset'in key or '_originalsize'in key): continue name = next((f for f in reversed(list(frames_dict.keys()))), None) if "_rect" in key: rect_info = list(map(int,value.split(','))) frames_dict[name]['rect']=(rect_info[0],rect_info[1], int(rect_info[2]),int(rect_info[3])) elif "_rotated" in key: frames_dict[name]["rotate"]=bool(value) elif "_trimmed" in key: frames_dict[name]["trim"]=value elif "offset" in key : offset_value=value.replace("{","").replace("}","") offsets=[float(x)for x in offset_value.split(",")] frames_dict[name]['offset']=tuple(offsets) elif "sourcecolor"not in key and"name"in locals(): del frames_dict[name] else:#new entry found frames_dict[value]={} name=value img=Image.open(image_path,'r') for k,v in frames_dict.items(): box=v['rect'] region=img.crop(box) if v.get('rotate',False): region=region.transpose(Image.ROTATE_90) out_file=os.path.join(output_dir,k+".png") dir_name=os.path.dirname(out_file) if not os.path.exists(dir_name): os.makedirs(dir_name) region.save(out_file,"PNG") if __name__ == '__main__': image_path='path/to/your/image.png' plist_path='path/to/your/file.plist' output_directory='./output' split_atlas(image_path=image_path, plist_path=plist_path, output_dir=output_directory) ``` 这段代码展示了如何解析给定路径下的`.plist`文件,并按照其描述裁剪相应的`.png`图像到指定目录下保存。需要注意的是实际项目中可能遇到更复杂的情况,因此建议在此基础上进一步完善脚本以适应特定场景的要求。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值