file_utils.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # -*- coding: utf-8 -*-
  2. from lib2to3.pytree import Node
  3. from math import floor
  4. import os
  5. import shutil
  6. import subprocess
  7. import xml.etree.ElementTree as ElementTree
  8. import plistlib
  9. #检查是否存在目录,没有则创建
  10. def checkDirectoryOrCreate(dir):
  11. if not os.path.exists(dir):
  12. os.makedirs(dir)
  13. #比较name中是否在suffix格式列表里
  14. #suffix为list,例如:['.png', '.mp3'],如suffix为None或者大小为0则直接返回True
  15. def __validExtension(name, suffix):
  16. if None == suffix:
  17. return True
  18. if len(suffix) <= 0:
  19. return True
  20. name = name.lower()
  21. for suffixTemp in suffix:
  22. if name.endswith(suffixTemp.lower()):
  23. return True
  24. return False
  25. #查找目录下指定类型的文件,忽略大小写
  26. #suffixList(数组)指定文件拓展名,例如:findFiles('../dir', False, ['.png', '.mp3']),如suffix为None或者大小为0则不过滤任何格式
  27. def findFiles(directory, includeChild, suffixList):
  28. ret = []
  29. if includeChild:
  30. for root, dirs, files in os.walk(directory):
  31. for name in files:
  32. if name.startswith('.'):
  33. continue
  34. if None == suffixList:
  35. temp = os.path.join(root, name)
  36. ret.append(temp)
  37. continue
  38. for suffixTemp in suffixList:
  39. if name.lower().endswith(suffixTemp.lower()):
  40. temp = os.path.join(root, name)
  41. ret.append(temp)
  42. break
  43. else:
  44. dirList = os.listdir(directory)
  45. for name in dirList:
  46. if name.startswith('.'):
  47. continue
  48. if None == suffixList:
  49. temp = os.path.join(directory, name)
  50. ret.append(temp)
  51. continue
  52. for suffixTemp in suffixList:
  53. if name.lower().endswith(suffixTemp.lower()):
  54. temp = os.path.join(directory, name)
  55. ret.append(temp)
  56. break
  57. return ret
  58. #搜集directory下的文件,拷贝到tarDirectory目录,注意tarDirectory里不保持与directory相同的目录结构
  59. #suffix(数组)指定文件拓展名,例如:copyFilesToDirectory('../dir', False, ['.png', '.mp3']),如suffix包含‘.*’则不过滤任何格式
  60. def copyToDirectory(directory, tarDirectory, includeChild, suffix):
  61. allFiles = findFiles(directory, includeChild, suffix)
  62. for curFile in allFiles:
  63. _, desFileName = os.path.split(curFile)
  64. desFile = os.path.join(tarDirectory, desFileName)
  65. shutil.copyfile(curFile, desFile)
  66. print(os.path.abspath(curFile))
  67. return len(allFiles)
  68. #指定Tps文件,调整缩放倍数,重新导出到指定目录下,如执行失败返回错误码
  69. def scaleTps(tpsFile, targetDir, scaleFactor):
  70. tpsFile = os.path.abspath(tpsFile)
  71. tree = ElementTree.parse(tpsFile)
  72. root = tree.getroot()
  73. textureFilePath = ''
  74. atalsFilePath = ''
  75. scaleRatio = 1.0;
  76. st = root.find('struct').getchildren()
  77. childCnt = len(st)
  78. for idx in range(0, childCnt):
  79. child = st[idx]
  80. if 'textureFileName' == child.text:
  81. textureFilePath = st[idx + 1].text
  82. elif 'dataFileName' == child.text:
  83. atalsFilePath = st[idx + 1].text
  84. elif 'dataFileNames' == child.text:
  85. atalsFilePath = st[idx + 1][1][1].text
  86. _, textureFileName = os.path.split(textureFilePath)
  87. _, atlasFileName = os.path.split(atalsFilePath)
  88. targetDir = os.path.abspath(targetDir)
  89. newTextureFile = os.path.join(targetDir, textureFileName)
  90. newAtalsFile = os.path.join(targetDir, atlasFileName)
  91. #获取原来的缩放系数
  92. for struct in root.iter('struct'):
  93. type = struct.attrib['type']
  94. if(type == 'SpriteSettings'):
  95. st = struct.getchildren()
  96. childCnt = len(st)
  97. for idx in range(0, childCnt):
  98. child = st[idx]
  99. if 'scale' == child.text:
  100. scaleRatio = float(st[idx + 1].text)
  101. print(scaleFactor*scaleRatio)
  102. cmd = "TexturePacker '%s' --scale %s --data '%s' --sheet '%s'" % (tpsFile, scaleFactor, newAtalsFile, newTextureFile)
  103. ret = os.system(cmd)
  104. if os.path.exists(newAtalsFile):
  105. print(atlasFileName)
  106. ext = os.path.splitext(atlasFileName)
  107. strExt = ext[len(ext) - 1]
  108. strExt = strExt.lower()
  109. if strExt == '.plist':
  110. f = open(newAtalsFile, 'rb')
  111. plistData = plistlib.load(f)
  112. #plistData['metadata']['scaleRatio'] = str(scaleFactor)
  113. plistData['metadata']['scaleRatio'] = '1'
  114. f.close()
  115. f = open(newAtalsFile, 'wb')
  116. plistlib.dump(plistData, f)
  117. f.close()
  118. return ret
  119. def scalePic(scaleFactor, inputFile, outputFile):
  120. inputFile = os.path.abspath(inputFile)
  121. outputFile = os.path.abspath(outputFile)
  122. cmd = "sips -g pixelWidth -g pixelHeight '%s'" % inputFile
  123. ret = os.popen(cmd).read().splitlines()
  124. tmp = ret[1].split(':')
  125. width = int(tmp[1]) * scaleFactor
  126. width = floor(width)
  127. tmp = ret[2].split(':')
  128. height = int(tmp[1]) * scaleFactor
  129. height = floor(height)
  130. if width < 1:
  131. width = 1
  132. if height < 1:
  133. height = 1
  134. cmd = "sips -z %d %d '%s' -o '%s'" % (height, width, inputFile, outputFile)
  135. os.system(cmd)
  136. def scalePicToDir(scaleFactor, inputFile, outputDir):
  137. _, fileName = os.path.split(inputFile)
  138. newFile = os.path.join(outputDir, fileName)
  139. scalePic(scaleFactor, inputFile, newFile)
  140. #缩放tps或者图片到指定的目录下
  141. def scaleTpsOrPicToDir(scaleFactor, searchDir, targetDir, includeChild):
  142. fileList = findFiles(searchDir, includeChild, ['.tps', '.png', '.jpg'])
  143. for curFile in fileList:
  144. _, ext = os.path.splitext(curFile)
  145. ext = ext.lower()
  146. if '.tps' == ext:
  147. scaleTps(curFile, targetDir, scaleFactor)
  148. else:
  149. scalePicToDir(scaleFactor, curFile, targetDir)