Skip to content

Instantly share code, notes, and snippets.

@vladimirgamalyan
Created June 28, 2015 08:37
Show Gist options
  • Save vladimirgamalyan/85aaf9253c663893015e to your computer and use it in GitHub Desktop.
Save vladimirgamalyan/85aaf9253c663893015e to your computer and use it in GitHub Desktop.
unpack TexturePacker .plist spritesheets
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import fnmatch
import plistlib
from PIL import Image
def plist_unpack(path):
print path
plist_dir = os.path.dirname(path)
dst_dir = os.path.splitext(path)[0]
plist = plistlib.readPlist(path)
texture_filename = os.path.join(plist_dir, plist['metadata']['textureFileName'])
sprite_sheet = Image.open(texture_filename)
for frame_name, frame_data in plist['frames'].items():
to_list = lambda x: x.replace('{', '').replace('}', '').split(',')
rotated = frame_data['rotated']
frame_list = to_list(frame_data['frame'])
frame_x = int(frame_list[0])
frame_y = int(frame_list[1])
frame_w = int(frame_list[2])
frame_h = int(frame_list[3])
if rotated:
frame_w, frame_h = frame_h, frame_w
source_size_list = to_list(frame_data['sourceSize'])
source_size_w = int(source_size_list[0])
source_size_h = int(source_size_list[1])
if rotated:
source_size_w, source_size_h = source_size_h, source_size_w
offset_list = to_list(frame_data['offset'])
offset_x = int(offset_list[0])
offset_y = int(offset_list[1])
result_image = Image.new('RGBA', [source_size_w, source_size_h], (0, 0, 0, 0))
result_box = (
int((source_size_w - frame_w) / 2 + offset_x),
int((source_size_h - frame_h) / 2 + offset_y),
int((source_size_w + frame_w) / 2 + offset_x),
int((source_size_h + frame_h) / 2 + offset_y)
)
sprite_sheet_rect = sprite_sheet.crop([frame_x, frame_y, frame_x + frame_w, frame_y + frame_h])
result_image.paste(sprite_sheet_rect, result_box, mask=0)
if rotated:
result_image = result_image.rotate(90)
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
dst_file = os.path.join(dst_dir, frame_name)
result_image.save(dst_file)
def parse_dir(path):
matches = []
for root, dir_names, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, '*.plist'):
matches.append(os.path.join(root, filename))
map(plist_unpack, matches)
if __name__ == '__main__':
arg = sys.argv[1] if len(sys.argv) == 2 else ''
if os.path.isdir(arg):
parse_dir(arg)
elif os.path.isfile(arg) and arg.lower().endswith('.plist'):
plist_unpack(arg)
else:
print "path to .plist file or directory required"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment