1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| from PIL import Image, ImageDraw, ImageFont from fontTools.ttLib import TTFont import os import string
def extract_and_save_characters_from_ttf(ttf_path, output_folder): font = TTFont(ttf_path) ttf = ImageFont.truetype(ttf_path, 40)
if not os.path.exists(output_folder): os.makedirs(output_folder)
def clean_filename(char, char_code): valid_chars = f"-_.() {string.ascii_letters}{string.digits}" cleaned = ''.join(c for c in char if c in valid_chars) return f"{cleaned}_{char_code}"
for table in font['cmap'].tables: for char_code in table.cmap: char = chr(char_code) image = Image.new('RGBA', (50, 50), (255, 255, 255, 0)) draw = ImageDraw.Draw(image) draw.text((10, 5), char, font=ttf, fill=(255, 255, 255, 255))
cleaned_char = clean_filename(char, char_code)
image.save(os.path.join(output_folder, f'{cleaned_char}.png'))
extract_and_save_characters_from_ttf(r'文件地址.ttf', 'output_folder')
|