xiaozi 2024-08-09 11:14:28

simplified.py 精简字体

#!/usr/bin/env python3

import os
import fontforge
import sys

# 常量
OUTPUT_FONT_NAME = "simplified.ttf"

def print_usage():
    """打印使用说明"""
    print("用法: fontforge -script script.py 字体文件 范围1 范围2 ...")
    print("示例: fontforge -script script.py PingFang.ttf 65-90 128")

def parse_ranges(args):
    """解析范围参数并返回元组列表"""
    total_array = []
    for arg in args:
        str_split = arg.split('-')
        try:
            if len(str_split) == 2:
                start = int(str_split[0])
                end = int(str_split[1])
                total_array.append((start, end))
            elif len(str_split) == 1:
                start = int(str_split[0])
                total_array.append((start, start))
            else:
                print(f"无效的范围格式: {arg}")
        except ValueError:
            print(f"范围中无效的数字: {arg}")
    return total_array

def open_font(font_path):
    """打开字体文件并返回字体对象"""
    print(f'正在打开 {font_path}')
    font = fontforge.open(font_path)
    font.reencode('unicode')
    return font

def select_glyphs_to_keep(font, ranges):
    """选择要保留的字形范围"""
    font.selection.none()  # 清除之前的选择
    for start, end in ranges:
        font.selection.select(("ranges", "unicode"), start, end)

def delete_unselected_glyphs(font):
    """删除未选择的字形并返回删除的字形数量"""
    font.selection.invert()  # 反转选择以选择要删除的字形
    num_glyphs = len(list(font.selection))
    font.clear()  # 删除选择的字形
    return num_glyphs

def generate_new_font(font, output_path, num_glyphs):
    """生成新的字体文件"""
    print(f'生成 {output_path},已删除 {num_glyphs} 个字形')
    font.generate(output_path, flags=("no-FFTM-table",))
    font.close()
    print(f'字体生成成功: {output_path}')

def main():
    if len(sys.argv) <= 2:
        print("参数不足!")
        print_usage()
        sys.exit(1)

    font_path = sys.argv[1]
    ranges = sys.argv[2:]

    total_array = parse_ranges(ranges)
    font = open_font(font_path)

    select_glyphs_to_keep(font, total_array)
    num_glyphs = delete_unselected_glyphs(font)

    generate_new_font(font, OUTPUT_FONT_NAME, num_glyphs)

if __name__ == "__main__":
    main()

评论

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.1. UTC+08:00, 2024-11-23 16:19
浙ICP备14020137号-1 $访客地图$