-
-
Save TkTech/dff9bbe54c9a074612e1 to your computer and use it in GitHub Desktop.
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
# -*- 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
Thanks for the correction. I believe when I posted this (9 years ago!) it was for python 2, which used a different default behavior for / vs //