Last active
February 17, 2024 13:27
-
-
Save snowyegret23/acc001287cb712ec3b43188051f5df6a to your computer and use it in GitHub Desktop.
bmfont의 fnt파일을 읽어서 폰트 정보/글리프 정보를 dict로 리턴 (txt로 export했을때 사용)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
# 정수인지 판별 | |
def isint(number): | |
try: | |
ret = int(number) | |
return True | |
except ValueError: | |
return False | |
# 리스트에서 "=" 기준으로 분리 후, 딕셔너리로 반환 | |
def lst_optimize(charlist): | |
tmp = charlist.split() | |
tmp = [i for i in tmp if "=" in i] | |
tmp_dict = {} | |
for i in tmp: | |
key = i.split("=")[0] | |
value = int(i.split("=")[1]) | |
tmp_dict[key] = value | |
return tmp_dict | |
# .fnt 파일 파싱해서 dict로 반환 | |
def parsing_fnt(fnt_path): | |
"""for parsing .fnt file (BMFont) | |
Args: | |
fnt_path (str): input .fnt file path | |
Returns: | |
dict: parsed .fnt file data. | |
Example: | |
data["header"]["face"] -> "나눔고딕" | |
Data: | |
data["header"] -> "face":str, "bold", "italic", "charset":str, | |
"unicode", "stretchH", "smooth", "aa", | |
"padding":list, "spacing":list, "outline", "lineHeight", | |
"base", "scaleW", "scaleH", "pages", "packed", | |
"alphaChnl", "redChnl", "greenChnl", "blueChnl" | |
"id", "file":str, "count" | |
data["char] -> "id", "x", "y", "width", "height", | |
"xoffset", "yoffset", "xadvance", "page", "chnl" | |
""" | |
with open(fnt_path, "r", encoding="utf-8") as f: | |
fnt_data = f.readlines() | |
# 헤더 데이터 분리 / 정리 | |
header_data = [ | |
i | |
for i in fnt_data | |
if i.startswith("char id") == False and i.startswith("kerning") == False | |
] | |
header_data = [i.strip() for i in header_data] | |
header_list = [j for i in header_data for j in i.split() if "=" in j] | |
header_dict = {} | |
for i in header_list: | |
key, value = i.split("=") | |
# value: 숫자 대응 (size=-15 -> "size": -15 // lineHeight=17 -> "lineHeight": 17) | |
if isint(value) == True: | |
header_dict[key] = int(value) | |
# value: 숫자 리스트 대응 (padding=0,0,0,0 -> "padding": [0,0,0,0]) | |
elif "," in value and '"' not in key: | |
value_numlist = [int(i) for i in value.split(",")] | |
header_dict[key] = value_numlist | |
# value: 문자열 대응 (face="나눔고딕" -> "face": "나눔고딕") | |
elif value.startswith('"'): | |
header_dict[key] = value.strip('"') | |
else: | |
header_dict[key] = value | |
# char 데이터 분리 / 정리 | |
char_list = [char.strip() for char in fnt_data if char.startswith("char id")] | |
char_dict = [lst_optimize(char) for char in char_list] | |
return {"header": header_dict, "char": char_dict} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment