Python + FontTools 自动生成字体子集工具 & FontForge 实现字体加粗

Python + FontTools 自动生成字体子集工具 & FontForge 实现字体加粗

一、创建项目目录

text 复制代码
fonttools/
│
├─ font_subset_core.py
├─ build.bat
└─ venv/

进入目录:

bat 复制代码
cd /d F:\tools\fonttools

二、创建虚拟环境

创建:

bat 复制代码
python -m venv venv

激活:

bat 复制代码
venv\Scripts\activate

成功后命令行会出现:

text 复制代码
(venv)

验证:

bat 复制代码
where python

输出应类似:

text 复制代码
F:\tools\fonttools\venv\Scripts\python.exe

三、安装依赖

安装 FontTools:

bat 复制代码
python -m pip install fonttools

安装 PyInstaller:

bat 复制代码
python -m pip install pyinstaller

验证 FontTools:

bat 复制代码
python -c "from fontTools.subset import main;print('OK')"

输出:

text 复制代码
OK

说明环境正常。


四、核心脚本 font_subset_core.py

python 复制代码
import sys
from pathlib import Path
from fontTools.subset import main as pyftsubset_main

FONT_EXTS = {".ttf", ".otf"}


def read_text_auto(path):
    data = Path(path).read_bytes()

    for enc in ("utf-8-sig", "utf-8", "gbk", "gb18030"):
        try:
            return data.decode(enc), enc
        except UnicodeDecodeError:
            pass

    return data.decode("gb18030", errors="ignore"), "gb18030-ignore"


def sort_key(c):
    code = ord(c)

    if '0' <= c <= '9':
        return (0, code)

    if 'A' <= c <= 'Z':
        return (1, code)

    if 'a' <= c <= 'z':
        return (2, code)

    if 0x4E00 <= code <= 0x9FFF:
        return (4, code)

    return (3, code)


def make_unique_chars(text):
    chars = {
        c
        for c in text
        if not c.isspace()
        and ord(c) >= 32
    }

    return "".join(sorted(chars, key=sort_key))


def build_subset(font_path, chars_path, out_font_path):
    pyftsubset_main([
        str(font_path),
        f"--text-file={chars_path}",
        f"--output-file={out_font_path}",
        "--layout-features=*",
        "--glyph-names",
        "--symbol-cmap",
        "--legacy-cmap",
        "--notdef-glyph",
        "--notdef-outline",`
        "--recommended-glyphs",
    ])


def main():
    if len(sys.argv) < 3:
        print("用法: font_subset_core.exe 字体.ttf 文本.txt")
        return

    font_path = Path(sys.argv[1])
    text_path = Path(sys.argv[2])

    if not font_path.exists():
        print("字体文件不存在:", font_path)
        return

    if not text_path.exists():
        print("文本文件不存在:", text_path)
        return

    if font_path.suffix.lower() not in FONT_EXTS:
        print("第一个参数必须是字体文件:", font_path)
        return

    text, enc = read_text_auto(text_path)
    chars = make_unique_chars(text)

    chars_path = text_path.with_name(text_path.stem + "_chars.txt")
    chars_path.write_text(chars, encoding="utf-8")

    out_font_path = font_path.with_name(font_path.stem + "_subset" + font_path.suffix)

    build_subset(font_path, chars_path, out_font_path)

    print("处理完成")
    print("识别编码 :", enc)
    print("字符数量 :", len(chars))
    print("字符文件 :", chars_path)
    print("子集字体 :", out_font_path)


if __name__ == "__main__":
    main()

命令格式:

bat 复制代码
python font_subset_core.py 字体.ttf 文本.txt

测试:

powershell 复制代码
python font_subset_core.py test.ttf test.txt
powershell 复制代码
处理完成
识别编码 : utf-8-sig
字符数量 : 247
字符文件 : test_chars.txt
子集字体 : test_subset.ttf
  • 自动完成
text 复制代码
读取文本
↓
去重
↓
排序
↓
生成 chars.txt
↓
调用 pyftsubset
↓
生成 subset.ttf

六、打包 EXE

使用 PyInstaller:

bat 复制代码
python -m PyInstaller -F --clean --collect-all fontTools --name FontSubset font_subset_core.py

参数说明:

text 复制代码
-F               单文件
--clean          清理缓存
--collect-all    打包 FontTools 全部依赖
--name           EXE名称

打包完成:

text 复制代码
dist/
└─ FontSubset.exe

FontSubset.exe 用于根据游戏文本自动生成字体子集。第一个参数为原始字体文件(支持 .ttf.otf),第二个参数为文本文件(.txt)。程序会自动读取文本内容、提取所有可见字符、去重排序、生成字符集文件,并调用内置的 pyftsubset 生成子集字体。

使用方式:

bat 复制代码
FontSubset.exe FZBWKS.ttf all_text.txt

执行后会生成:

text 复制代码
all_text_chars.txt     // 去重后的字符集
FZBWKS_subset.ttf      // 生成的子集字体

适用于传奇游戏、手游项目、UI字体优化等场景,可大幅缩小字体体积,同时保留项目实际使用到的全部字符。


无需安装:

text 复制代码
Python
FontTools
PyInstaller

用户机器直接运行即可。


七、 字体加粗

安装 FontForge

下载地址

然后打开上面生成的字体子集。勾选如下红框可紧凑显示(忽略空格只显示有的字符)

设置

Ctrl + A 全选,然后调整字体实现加粗。中文选 CJK 字中空隙保留选 Retain

我用 6 em units 这个要自己调看效果

导出

将选中字符导出为字体文件(警告什么的,反正也不会处理,直接跳过)

参考资料

https://github.com/fontforge/fontforge

相关推荐
2601_962299241 小时前
Azure python操作系统列表
python·操作系统·azure·虚拟机·存储配置文件
学术 学术 Fun2 小时前
如何用 API 与 Webhook 批量把图表图片转换成 VSDX
python·自动化·api·visio
2601_962100543 小时前
python包和模块的内容整理
python·模块·导入·虚拟环境·
二进制漫游记3 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
-今昭-4 小时前
《V2V 迁移实战:将 VMware 虚拟机转为 OpenStack 可用 Glance qcow2 镜像》
开发语言·python
2601_962381584 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全
用户3721574261354 小时前
如何使用 Python 从 Word 文档中提取图片
python
白山编程大哥6 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
昭昭日月明7 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程
莓有烦恼吖8 小时前
Vibe Coding 的一些思考
python