Skip to content

Instantly share code, notes, and snippets.

@vladimirgamalyan
Created July 13, 2015 12:48
Show Gist options
  • Save vladimirgamalyan/0bbd0a900ce7ab8260f7 to your computer and use it in GitHub Desktop.
Save vladimirgamalyan/0bbd0a900ce7ab8260f7 to your computer and use it in GitHub Desktop.
unpack bmfont texture
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from PIL import Image
import xml.etree.ElementTree as ElementTree
def unpack_fnt(f):
root = ElementTree.parse(f).getroot()
fnt_dir = os.path.dirname(f)
dst_dir = os.path.join(fnt_dir, 'unpacked')
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
pages = {}
for page in root.find('pages').iter('page'):
pages[page.attrib['id']] = Image.open(os.path.join(fnt_dir, page.attrib['file']))
for char in root.find('chars').iter('char'):
name = '_' + char.attrib['id'] + '.png'
dst_file = os.path.join(dst_dir, name)
width = int(char.attrib['width'])
height = int(char.attrib['height'])
x = int(char.attrib['x'])
y = int(char.attrib['y'])
x_offset = int(char.attrib['xoffset'])
y_offset = int(char.attrib['yoffset'])
x_advance = int(char.attrib['xadvance'])
w = width + x_offset
if w < x_advance:
w = x_advance
glyph = Image.new('RGBA', [w, height + y_offset])
glyph.paste(pages[char.attrib['page']].crop((x, y, x + width, y + height)), (x_offset, y_offset))
glyph.save(dst_file)
if __name__ == '__main__':
if len(sys.argv) == 2:
fnt_file = sys.argv[1]
if os.path.isfile(fnt_file):
unpack_fnt(fnt_file)
else:
print "can't find .fnt file"
else:
print "usage: script.py <path to .fnt file>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment