Skip to content

Instantly share code, notes, and snippets.

@aelam
Created April 22, 2016 15:15
Show Gist options
  • Save aelam/b22a072aee24e835ed3202749e1ee21b to your computer and use it in GitHub Desktop.
Save aelam/b22a072aee24e835ed3202749e1ee21b to your computer and use it in GitHub Desktop.
image_rename.py
#!/usr/bin/env python
# -*-encoding:utf-8-*-
import json
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def process_imagesets_in_paths(imagesets_dirs):
for dir in imagesets_dirs:
process_imagesets(dir)
def process_imagesets(imagesets_dir):
print "[PROCESSING IMAGESETS]: " + imagesets_dir
find_imagesets(imagesets_dir)
print "[DONE IMAGESETS]: " + imagesets_dir
def find_imagesets(dir):
# for root, dirs, files in os.walk(dir, topdown=True):
for root, _, _ in os.walk(dir, topdown=True):
if os.path.isdir(root) and root.endswith(".imageset"):
process_imageset(root)
def process_imageset(imageset_path):
contents_json_path = imageset_path + "/Contents.json"
if not os.path.exists(contents_json_path):
log_image_set_empty(contents_json_path)
return
# Reading data
with open(contents_json_path, 'r') as f:
contents_json = json.load(f)
print "[Reading JSON] " + contents_json_path + " ..."
# Get imageset name
imageset_fullname = os.path.basename(imageset_path)
image_set_name, ext = os.path.splitext(imageset_fullname)
# Get image info from json and rename image names
images = contents_json["images"]
has_change = False
for image in images:
# rename file
if u'filename' in image:
old_file_name = image[u'filename']
if old_file_name is None:
#print "[NO MODIFYING] No image under scale:" + image["scale"]
continue
else:
new_file_name = image_set_name + "@" + image["scale"] + ".png"
if old_file_name != new_file_name:
old_image_path = os.path.join(imageset_path, old_file_name)
new_image_path = os.path.join(imageset_path, new_file_name)
os.rename(old_image_path, new_image_path)
image["filename"] = new_file_name
has_change = True
print "[Updating image name] " + old_file_name + " --> " + new_file_name
#else:
#print "[NO MODIFYING] They have a same name with imagesets: " + image_set_name
has_change = True
if has_change:
print "[Writing new JSON] " + contents_json_path
with open(contents_json_path, 'w') as f:
json.dump(contents_json, f, indent=2, separators=(',',' : '))
else:
print "[ALREADY A GREAT IMAGESETS] " + contents_json_path
# write new json
def log_image_set_empty(file):
print "[Error]Imageset is Empty: " + file
if __name__ == '__main__':
#path = os.path.join(os.getcwd(), "simple.xcassets")
#print(path)
#process_imagesets_in_paths([path])
if len(sys.argv) >= 2:
paths = sys.argv[1:]
process_imagesets_in_paths(paths)
else:
print "args required"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment