zoukankan      html  css  js  c++  java
  • 还原TexturePacker plist 文件以及图片的方法 (切开各小图片)

    原地址:http://blog.csdn.net/linuxchen/article/details/16865645

    Python 脚本:(来自网络)

    unpack_plist.py

    命令行: python unpack_plist.py  plist文件名称 

    例子: python unpack_plist.py  common      ## plist文件全名为 common.plist

    [python] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. #!python  
    2. import os,sys  
    3. from xml.etree import ElementTree  
    4. from PIL import Image  
    5.   
    6. def tree_to_dict(tree):  
    7.     d = {}  
    8.     for index, item in enumerate(tree):  
    9.         if item.tag == 'key':  
    10.             if tree[index+1].tag == 'string':  
    11.                 d[item.text] = tree[index + 1].text  
    12.             elif tree[index + 1].tag == 'true':  
    13.                 d[item.text] = True  
    14.             elif tree[index + 1].tag == 'false':  
    15.                 d[item.text] = False  
    16.             elif tree[index+1].tag == 'dict':  
    17.                 d[item.text] = tree_to_dict(tree[index+1])  
    18.     return d  
    19.   
    20. def gen_png_from_plist(plist_filename, png_filename):  
    21.     file_path = plist_filename.replace('.plist', '')  
    22.     big_image = Image.open(png_filename)  
    23.     root = ElementTree.fromstring(open(plist_filename, 'r').read())  
    24.     plist_dict = tree_to_dict(root[0])  
    25.     to_list = lambda x: x.replace('{','').replace('}','').split(',')  
    26.     for k,v in plist_dict['frames'].items():  
    27.         rectlist = to_list(v['frame'])  
    28.         width = int( rectlist[3] if v['rotated'] else rectlist[2] )  
    29.         height = int( rectlist[2] if v['rotated'] else rectlist[3] )  
    30.         box=(   
    31.             int(rectlist[0]),  
    32.             int(rectlist[1]),  
    33.             int(rectlist[0]) + width,  
    34.             int(rectlist[1]) + height,  
    35.             )  
    36.         sizelist = [ int(x) for x in to_list(v['sourceSize'])]  
    37.         rect_on_big = big_image.crop(box)  
    38.   
    39.         if v['rotated']:  
    40.             rect_on_big = rect_on_big.rotate(90)  
    41.   
    42.         result_image = Image.new('RGBA', sizelist, (0,0,0,0))  
    43.         if v['rotated']:  
    44.             result_box=(  
    45.                 ( sizelist[0] - height )/2,  
    46.                 ( sizelist[1] - width )/2,  
    47.                 ( sizelist[0] + height )/2,  
    48.                 ( sizelist[1] + width )/2  
    49.                 )  
    50.         else:  
    51.             result_box=(  
    52.                 ( sizelist[0] - width )/2,  
    53.                 ( sizelist[1] - height )/2,  
    54.                 ( sizelist[0] + width )/2,  
    55.                 ( sizelist[1] + height )/2  
    56.                 )  
    57.         result_image.paste(rect_on_big, result_box, mask=0)  
    58.   
    59.         if not os.path.isdir(file_path):  
    60.             os.mkdir(file_path)  
    61.         outfile = (file_path+'/' + k).replace('gift_', '')  
    62.         print outfile, "generated"  
    63.         result_image.save(outfile)  
    64.   
    65. if __name__ == '__main__':  
    66.     filename = sys.argv[1]  
    67.     plist_filename = filename + '.plist'  
    68.     png_filename = filename + '.png'  
    69.     if (os.path.exists(plist_filename) and os.path.exists(png_filename)):  
    70.         gen_png_from_plist( plist_filename, png_filename )  
    71.     else:  
    72.         print "make sure you have boith plist and png files in the same directory"  


    windows7 下相关python配置:

    1. 安装python2.7.3

    2. 在此处下载 安装 (这是最简洁的方式,已经编译好png,zip等处理) 

     http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

     https://pypi.python.org/pypi/Pillow/2.2.1#downloads

    http://download.csdn.net/detail/liuheng123456/6235465

    http://blog.afantree.com/python/python2-split-plist-spritesheet.html

     昨天写了Zwoptex生成精灵表,有合就有分,能不能把合成的文件再原模原样的还原回来,哈哈……于是,今天利用闲暇的时间想一个问题:plist是用xml格式的,强大的python中的PIL(Python Imaging Library)可以处理各种图片,更不用说png图片了。
      昨天分析过plist,除了一个名字外,今天还能用上的还有两个属性,原始的文件的尺寸大小(这必须得要)和纹理在精灵表中的位置和大小,因为对xml的操作不太多,只是读取数据,就选用轻量级的ElementTree,把从xml解析出来的字符串数据转换成int类型,这就得到了图片属性的真实数据,这在精灵表上复制那个区域内的图片,然后在粘贴到新建的图片里面,哈哈,这样就搞定了。
      在操作的时候会用到PIL库,点击下载PIL
      大概的思路是说出来啦,最实在的还是把代码粘贴出来,运行一下看看:

    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    #encoding=utf-8
    import os,Image,sys
    from xml.etree import ElementTree
    filenames=os.listdir(os.getcwd())
    i=0
    if len(sys.argv)==2:
        filepath=sys.argv[1]
        for filename in filenames:
            if (filename==filepath+'.png') or (filename==filepath+'.plist'):
                i +=1
        if i==0:
            print("No such file or directory!")
        elif i==1:
            print("Both .png and .plist are need!")
        else:
            treeroot=ElementTree.parse(filepath+'.plist').getroot()
            #p=list(per.iter("key"))
            image=Image.open(filepath+'.png'#open image
            sizelist=(0,0)
     
            #box=(0,0,0,0)
     
            for dict1 in treeroot:
                for index1,item1 in enumerate(dict1): #
            #        print (item1.tag,item1.attrib,item1.text)
                    if item1.text=='frames'#get node who Value=frames
            #            print (index1)
                        i=0
                        dict2 = dict1[index1+1]
            #            print(len(dict2))
            #            for index2,item2 in enumerate(dict2):
            #                print(item2.tag,item2.attrib,item2.text)
                        while i<len(dict2):
                            print("name:"+dict2[i].text)
                            picname=dict2[i].text
                            dict3 = dict2[i+1]
                            for index3,item3 in enumerate(dict3):
            #                    print(item3.tag,item3.attrib,item3.text)
                                if item3.text=='spriteSourceSize':
            #                        print(dict3[index3+1].text)
                                    size=dict3[index3+1].text
                                    sizelist = size.replace('{','').replace('}','').split(',')
                                    sizelist=(int(sizelist[0]),int(sizelist[1]));
                                    #print(sizelist)
                                     
                                if item3.text=='textureRect':
            #                        print(dict3[index3+1].text)
                                    rect=dict3[index3+1].text
                                    rectlist = rect.replace('{','').replace('}','').split(',')
            #                        print(rectlist)
                                    box=(int(rectlist[0]),int(rectlist[1]),int(rectlist[0])+int(rectlist[2]),int(rectlist[1])+int(rectlist[3]))
                                    print("size:")
                                    print(sizelist)
                                    print("onBig:")
                                    print(box)
                                    xim=image.crop(box)
                                    xxim=Image.new('RGB',sizelist,(255,255,255))
                                    box1=((sizelist[0]-box[2]+box[0])/2,(sizelist[1]-box[3]+box[1])/2,(sizelist[0]+box[2]-box[0])/2,(sizelist[1]+box[3]-box[1])/2)
                                    print("onNew:")
                                    print(box1)
                                    xxim.paste(xim,box1,mask=0)
                                    if os.path.isdir(filepath):
                                        pass
                                    else:
                                        os.mkdir(filepath)
                                    outfile=filepath+'/'+picname
                                    print("newPath:"+outfile)
                                    xxim.save(outfile)
                            i +=2
    else:
        print("Please enter only one parameter!")

    里面的print比较多,因为怕出错了不好找,就写几步,print出来看看数据对不对。
      复制这段代码,保存,然后在终端写:python xx.py file(就是想分割的文件名,不加后缀)。
      本人运行环境:Mac OSX10.7,python 2.7.3,PIL 1.1.7,完美通过!
      

    http://coastline.freepgs.com/archives/275

    参考网址1:http://blog.afantree.com/python/python2-split-plist-spritesheet.html

    结果:doesn’t work on python 2.7,报错     ==>作者已经修正该问题,有兴趣的朋友可以进入以上链接尝试他的方案。   ==>该文的方案适用于由Zwoptex制作的png+plist,有兴趣的朋友请移步。

    参考网址2:http://stackoverflow.com/a/17838628

    结果:不够完善,兼容性不好,于是我又经过了一点修改后,终于在python 2.7下成功。如果你的大图是pvr,需要先用Texture Packer转成png。

    下面记录一下步骤:

      • 安装PIL(Python Imaging Library)
        附上Mac上自己编译安装PIL的步骤:
        1.在xcode中安装命令行工具,如果你尚未安装过的话
        2.curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
        3.tar -xzf Imaging-1.1.7.tar.gz
        4.cd Imaging-1.1.7
        5.python setup.py build
        6.sudo python setup.py install
      • 保存以下内容至split_png_plist.py
        #! /usr/lical/bin/python
        import os,Image,sys
        from xml.etree import ElementTree
        
        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():
                print "-----start
        ----------"
                rectlist = to_list(v['frame'])
                print rectlist, "--------rectlist"
                width = int( rectlist[3] if v['rotated'] else rectlist[2] )
                height = int( rectlist[2] if v['rotated'] else rectlist[3] )
                print width,height,"----width,height"
                box=( 
                    int(rectlist[0]),
                    int(rectlist[1]),
                    int(rectlist[0]) + width,
                    int(rectlist[1]) + height,
                    )
                # bos is start & end point
                print box,"-----_box-"
                print v['rotated'], "---rotated"
        
                sizelist = [ int(x) for x in to_list(v['sourceSize'])]
                rect_on_big = big_image.crop(box)
                '''
                result_image = Image.new('RGBA', sizelist, (0,0,0,0))
                result_box=(
                    ( sizelist[0] - width )/2,
                    ( sizelist[1] - height )/2,
                    ( sizelist[0] + width )/2,
                    ( sizelist[1] + height )/2
                    )
                result_image.paste(rect_on_big, result_box, mask=0)
                if v['rotated']:
                    result_image = result_image.rotate(90)
                if not os.path.isdir(file_path):
                    os.mkdir(file_path)
                outfile = (file_path+'/' + k).replace('gift_', '')
                print result_box,"-----result_box-"
                print outfile, "generated"
                # result_image.save(outfile)
                '''
        
                if v['rotated']:
                    rect_on_big = rect_on_big.rotate(90)
                if not os.path.isdir(file_path):
                    os.mkdir(file_path)
                outfile = (file_path+'/' + k).replace('gift_', '')
                if not outfile.lower().endswith('.png'):   #PIL fails if no extension
                    outfile += ".png";
                print "saving:" + outfile;
                rect_on_big.save(outfile);
                print "saved:" + 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"
      • 将该py文件和你的xxx.png、xxx.plist放在同一目录下,终端中运行:
        python split_png_plist.py xxx
      • 一切顺利的话,当前目录下会生成名为xxx的目录,里面就是分割出来的各png小图
  • 相关阅读:
    Sublime Text 3 使用总结
    全选,不选,反选 jquery
    表格展开
    JavaScript中的window对象
    《JS权威指南学习总结--第十一章子集和扩展》
    《JS正则表达式》
    《JS中的面向对象技术》
    《JS权威指南学习总结--9.5 类和类型》
    prototype属性的理解
    《JS权威指南学习总结--9.3 JS中JAVA式的类继承》
  • 原文地址:https://www.cnblogs.com/123ing/p/3920489.html
Copyright © 2011-2022 走看看