还原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
- 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
- )
- 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"
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-8importos,Image,sysfromxml.etree importElementTreefilenames=os.listdir(os.getcwd())i=0iflen(sys.argv)==2:    filepath=sys.argv[1]    forfilename infilenames:        if(filename==filepath+'.png') or(filename==filepath+'.plist'):            i +=1    ifi==0:        print("No such file or directory!")    elifi==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)        fordict1 intreeroot:            forindex1,item1 inenumerate(dict1): #        #        print (item1.tag,item1.attrib,item1.text)                ifitem1.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)                    whilei<len(dict2):                        print("name:"+dict2[i].text)                        picname=dict2[i].text                        dict3 =dict2[i+1]                        forindex3,item3 inenumerate(dict3):        #                    print(item3.tag,item3.attrib,item3.text)                            ifitem3.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)                                                            ifitem3.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)                                ifos.path.isdir(filepath):                                    pass                                else:                                    os.mkdir(filepath)                                outfile=filepath+'/'+picname                                print("newPath:"+outfile)                                xxim.save(outfile)                        i +=2else:    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\n----------"
 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小图
还原TexturePacker plist 文件以及图片的方法 (切开各小图片)的更多相关文章
- 使用 jQuery 操作页面元素的方法,实现浏览大图片的效果,在页面上插入一幅小图片,当鼠标悬停到小图片上时,在小图片的右侧出现与之相对应的大图片
		查看本章节 查看作业目录 需求说明: 使用 jQuery 操作页面元素的方法,实现浏览大图片的效果,在页面上插入一幅小图片,当鼠标悬停到小图片上时,在小图片的右侧出现与之相对应的大图片 实现思路: 在 ... 
- 像素 PIXEL 图片的基本单位 像素非常小 图片是成千上万的像素组成  显示/屏幕分辨率 (DPI 屏幕分辨率)
		像素 PIXEL 图片的基本单位 像素非常小 图片是成千上万的像素组成 显示/屏幕分辨率 (DPI 屏幕分辨率) 图像分辨率 (PPI) 1920*1080是像素点长度1920个像素点 X1080个像 ... 
- plist文件Boolean类型读写方法
		http://blog.csdn.net/a6472953/article/details/7659505 转 1.读取plist文件中的Boolean类型的字段值时,要先把它转为NSNumber ... 
- ios cocos2d TexturePacker生成文件后的使用方法
		(1)将*.pvr.ccz文件转换为CCSpriteBatchNode (2) 将对应的plist文件读到CCSpriteFrameCache中 (3) 从CCSpriteFrameCache获取 ... 
- plist文件真机写入方法
		http://blog.csdn.net/mydo/article/details/50290219 转 但是这对真机不管用,因为在真机环境下,App在Xcode中的Resources文件夹都是不可 ... 
- iOS 图片压缩方法
		iOS 图片压缩方法 两种图片压缩方法 两种压缩图片的方法:压缩图片质量(Quality),压缩图片尺寸(Size). 压缩图片质量 NSData *data = UIImageJPEGReprese ... 
- css网页中设置背景图片的方法详解
		在css代码中设置背景图片的方法,包括背景图片.背景重复.背景固定.背景定位等 用css设置网页中的背景图片,主要有如下几个属性: 1,背景颜色 {">说明:参数取值和颜色属性一样 ... 
- iOS 打包.framework(包括第三方、图片、xib、plist文件)详细步骤及需要注意的地方
		https://www.cnblogs.com/yk123/p/9340268.html // 加载自定义名称为Resources.bundle中对应images文件夹中的图片// 思路:从mainb ... 
- 自定义TexturePacker插件导出自己的plist文件
		原地址:http://www.cppblog.com/sunicdavy/archive/2014/02/06/205645.html cocos2dx引擎使用plist文件, 一种特殊的xml格式作 ... 
随机推荐
- ORACLE DG之参数详解
			1.DB_NAME 数据库名字,需要保持同一个Data Guard中所有数据库DB_NAME相同. 主库和备库相同 DB_NAME='chicago' DB_NAME='chicago' 2.DB_U ... 
- Keil的使用方法 - 常用功能(二)
			Ⅰ.概述 上一篇文章是总结关于Keil使用方法-常用功能(一),关于(文件和编译)工具栏每一个按钮的功能描述和快捷键的使用. 我将每一篇Keil使用方法的文章都汇总在一起,回顾前面的总结请点击下面的链 ... 
- ListView用法及加载数据时的闪烁问题和加载数据过慢问题
			ListView介绍及添加数据时的闪烁问题 1. ListView类 1.1 ListView常用的基本属性: (1)FullRowSelect:设置是否行选择模式.(默认为false) 提示 ... 
- 刀哥多线程现操作gcd-10-delay
			延迟操作 // MARK: - 延迟执行 - (void)delay { /** 从现在开始,经过多少纳秒,由"队列"调度异步执行 block 中的代码 参数 1. when 从现 ... 
- ThinkPHP3.2.2中开启REWRITE模式
			1. 在项目配置文件(\Application\Common\Conf\config.php)中配置URL模式 <?php return array( //URL模式 , ); 2. 在Thin ... 
- meteor 实现 微信分享
			Template.hello.events({ 'click button': function () { // increment the counter when button is clicke ... 
- Go语言工程结构
			Go是一门推崇软件工程理念的编程语言. Go的代码必须放在GOPATH目录下,它应该包含三个子目录: src:用于以代码包的形式组织并保存Go源码文件.应该分为三类:库源码文件.命令源码文件.测试源码 ... 
- linux系统下sd卡的备份与恢复
			linux系统下sd卡的备份与恢复 现在各种的开发板都是从sd卡上面启动的,因此大修改工作之前很有必要备份一下. 备份 在linux系统下用读卡器读取sd卡 用df -h命令看分区的路径 一般都是/d ... 
- UIStepper swift
			// // ViewController.swift // UILabelTest // // Created by mac on 15/6/23. // Copyright (c) 2015年 fa ... 
- activemq整合spring
