Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# -*- coding: utf-8 -*-
import struct
from collections import namedtuple
from PIL import Image
Column = namedtuple('Column', 'start end')
Box = namedtuple('Box', [
'source',
'top_left',
'bottom_left',
'top_right',
'bottom_right'
])
class PreRenderedFonts(object):
#: Width (in pixels) of the pre-rendered PNG.
GLYPH_PAGE_WIDTH = 256
#: Height (in pixels) of the pre-rendered character.
GLYPH_HEIGHT = 16
def __init__(self, source):
self._sizes = [Column(
b >> 4,
b & 0x0F
) for b in struct.unpack('65536b', source.read(65536))]
@property
def sizes(self):
return self._sizes
def box_for_unicode(self, unicode_char):
unicode_value = ord(unicode_char)
if unicode_value > 65536:
# Only the first 65536 characters are mapped.
return None
try:
size = self.sizes[unicode_value]
except KeyError:
return None
if size == (0, 0):
# There's no mapping for this particular character.
return None
start_x = (unicode_value % 16) * (self.GLYPH_PAGE_WIDTH / 16)
start_x += size.start
start_y = ((unicode_value & 0xFF) / 16) * (self.GLYPH_PAGE_WIDTH / 16)
width = (size.end + 1) - size.start
return Box(
'unicode_page_{page:02x}.png'.format(
page=int(unicode_value / 256)
),
(start_x, start_y),
(start_x, (start_y + self.GLYPH_HEIGHT)),
((start_x + width), start_y),
((start_x + width), (start_y + self.GLYPH_HEIGHT))
)
with open('assets/minecraft/font/glyph_sizes.bin', 'rb') as source:
prf = PreRenderedFonts(source)
source_and_box = prf.box_for_unicode(u'\u00E9')
print(source_and_box)
im = Image.open('assets/minecraft/textures/font/{page}'.format(
page=source_and_box.source
))
cropped_im = im.crop(
source_and_box.top_left + source_and_box.bottom_right
)
cropped_im.save('tmp.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.