FreeTypeで文字を書く(3) - らんだむな記憶の続き。
def save_image(gid): face = freetype.Face(font_path) face.set_char_size(224*64) W, H = 224, 224 Z = np.zeros( (H, W), dtype=np.ubyte ) face.load_glyph(gid) bitmap = face.glyph.bitmap x, y = face.glyph.bitmap_left, face.glyph.bitmap_top w, h, p = bitmap.width, bitmap.rows, bitmap.pitch shift = -face.descender * self.size // face.units_per_EM y += shift buff = np.array(bitmap.buffer, dtype=np.ubyte).reshape((h,p)) Z[H-y:H-y+h,x:x+w].flat |= buff[:,:w].flatten() Z = 0xff - Z im = Image.fromarray(Z, mode="L") #im = im.convert("L").convert("RGB") im.save(f"{gid}.png", "PNG")
で大体いいんじゃないかな。 face.descender
や face.units_per_EM
は F26Dot6
ではなく Python の普通の数値型として返ってくるのである意味では対称性がないな。与える時は F26Dot6
で、得る時は Python の普通の数値型って感じなのかな。
face.descender
の分だけ調整するのは CJK フォントでは表意文字の部分のベースラインが y = 0
ではなく y = descender
なので上に移動させて調整するという補正。