分割带有plist的图片(TexturePacker)

来源:互联网 发布:php 接口开发框架 编辑:程序博客网 时间:2024/05/19 17:58

在cocos2dx开发中经常用到带有plist的图片集,虽然已经有了相应工具Anti_TexturePacker,还是想尝试了自己写了一个。

因为plist是xml文件,所以需要用到python的ElementTree解析xml。

texture.py:

try:     import xml.etree.cElementTree as ET except ImportError:     import xml.etree.ElementTree as ET import reimport syspng_list = []def loadpng(PngName):    tree = ET.parse(PngName+ '.plist')    root = tree.getroot()    for kk in root.findall('dict'):        for i in range(len(kk)):            if kk[i].text == "frames":                pngv = kk[i+1]                for j in  range(len(pngv)):                    png_dict = {}                    if pngv[j].tag == 'key':                        # 把图片名称加入 dict                        png_dict['png'] = pngv[j].text                        png_list.append(png_dict)                        frame = pngv[j+1]                        for k in range(len(frame)):                            if frame[k].text == 'frame':                                # 把图片 坐标和 宽高加入 dict                                png_dict['pos'] = frame[k+1].text                            if frame[k].text == 'rotated':                                # 图片 是否旋转                                png_dict['rotated'] = frame[k+1].tag    return splitpng()def splitpng():    # 过滤掉 位置字符串中的{}    m = re.compile(u'[^{}]+')    image_list = []    for d in png_list:        tmp = {}        tmp['png'] = d['png']        tmp['rotated'] = d['rotated']        pos = d['pos'].split(',')        pos_dict = {}        for i in range(len(pos)):            cn = m.findall(pos[i] )            if i == 0:                pos_dict['x'] = cn[0]            elif i == 1:                pos_dict['y'] = cn[0]            elif i == 2:                pos_dict['w'] = cn[0]            elif i == 3:                pos_dict['h'] = cn[0]        tmp['pos'] = pos_dict        image_list.append(tmp)    return image_list

texture.py文件用于获取小图片的名称、坐标、宽高和旋转信息的dict

splitimage.py:

from PIL import Imagefrom texture import loadpngimport os PngName = "mainlayer"def splitImg():    # 创建同名文件夹,如果已经存在,则无需创建    if os.path.exists(PngName) == False:        os.mkdir(PngName)    im = Image.open(PngName +'.png')    image_list = loadpng(PngName)    for img in image_list:        png_name = img['png']    #每个小图片的名字        pos = img['pos']         #每个小图片的坐标、长宽、是否旋转信息        if img['rotated'] == 'true':            box = ( int(pos['x']), int(pos['y']),  int(pos['x'])+int(pos['h']) ,int(pos['y']) + int(pos['w']) )        else:            box = ( int(pos['x']), int(pos['y']), int(pos['x']) + int(pos['w']), int(pos['y'])+int(pos['h']))        region  = im.crop(box)        if img['rotated'] == 'true':            region = region.transpose(Image.ROTATE_90)        region.save(PngName + '/' + png_name)if __name__ == '__main__':    splitImg()

splitimage.py使用了Pillow模块,根据相应的坐标等信息,切割图片,然后保存。

总结:

这里并不够完善,因为plist文件名称是写在代码里。可以继续完善的,不过,我只是练手用的,就告一段落了。

阅读全文
0 0