Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, sys, fnmatch, json, shutil
- from PIL import Image
- class XCAssetImage:
- def __init__(self,size,scale,idiom,filename):
- self.size = size
- self.scale = scale
- self.idiom = idiom
- self.filename = filename+'_'+str(self.size)+'_'+str(self.scale)+'x.png'
- def to_json(self):
- jsonDict = {}
- jsonDict['size'] = str(self.size)+'x'+str(self.size)
- jsonDict['idiom'] = self.idiom
- jsonDict['filename'] = self.filename
- jsonDict['scale'] = str(self.scale)+'x'
- # print jsonDict
- return jsonDict
- def emptyDir(directory):
- for root, dirs, files in os.walk(directory):
- for f in files:
- os.unlink(os.path.join(root, f))
- for d in dirs:
- shutil.rmtree(os.path.join(root, d))
- def findFiles(projectPath):
- pattern = 'AppIcon.appiconset'
- for root, dirnames, filenames in os.walk(projectPath):
- for directory in dirnames:
- if pattern in directory:
- print 'found file'
- fullPath = os.path.join(root, directory)
- print fullPath
- return fullPath
- def makeImage(source_img,asset):
- try:
- pixels = asset.size*asset.scale
- size = (pixels,pixels)
- source_img.thumbnail(size)
- source_img.save(asset.filename, "PNG")
- successStr = 'created image for size ' + str(size)
- print successStr
- except IOError:
- errStr = 'cannot create image for size ' + str(size)
- print errStr
- return
- def generate_assets(filename, iconsetPath):
- contentsPath = iconsetPath + '/Contents.json'
- print contentsPath
- contents = open(contentsPath, 'r')
- spec = json.load(contents)
- prettyPrint(spec)
- assets = []
- for imageObject in spec['images']:
- size = imageObject['size']
- size = size.split('x').pop(0)
- scale = imageObject['scale']
- scale = scale.split('x').pop(0)
- asset = XCAssetImage(int(size),int(scale),imageObject['idiom'],filename)
- assets.append(asset)
- return assets
- def prettyPrint(jsonObj):
- print json.dumps(jsonObj,sort_keys=True,indent=4,separators=(',', ': '))
- def writeContents(assets):
- jsonDict = {}
- jsonDict['info'] = {
- 'version' : 1,
- 'author' : 'xcode'
- }
- images = []
- for a in assets:
- images.append(a.to_json())
- jsonDict['images'] = images
- prettyPrint(jsonDict)
- with open('Contents.json', 'w') as outfile:
- json.dump(jsonDict, outfile)
- def main():
- #intended invocation:
- #python make_images.py <imagename (relative to script location)> <project path>
- #python make_images.py DBAppIcon2.png /Users/niko/Documents/DuncansBurgers
- argsList = sys.argv
- if len(argsList) < 3:
- exit('not enough args')
- path = argsList.pop()
- imgName = argsList.pop()
- fileName = os.path.splitext(imgName)[0]
- newDir = findFiles(path)
- assets = generate_assets(fileName, newDir)
- emptyDir(newDir)
- source_img = Image.open(imgName)
- os.chdir(newDir)
- for a in assets:
- img = source_img.copy()
- makeImage(img,a)
- writeContents(assets)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement