如何子集化壓縮字體

你是第個看到這篇文章的哦~

教程

目標

本文將實現:

1. 環境配置

2. 安裝FontTools

3. 創建字符文件

4. 壓縮字體

準備工作

你需要:

1. 一個字體文件(.ttf)

2. 一臺電腦或手機termux

tips:此教程的表述主要以Windows為主,命令win、linux通用,用 綠色粗體 標識的可以根據實際情況更改

檢查環境

Win+R輸入cmd回車

輸入 python --versionpython3 --version

如果顯示python x.x.x說明已經有啦

如果沒有顯示這個:Windows用戶請到Python官網下載,安裝時記得勾選add python to path;linux用戶應該不用我教了叭(

安裝FontTools

在cmd輸入 pip install fonttools brotli 如果安裝了多個python:pip3 install fonttools brotli

輸入 pyftsubset --help 如果顯示幫助表示安裝成功

創建字符文件

創建一個 txt 文件,並在裡面輸入你網頁會用到的字符,例如:查看

tips:你也可以通過 Unicode 範圍生成字符

以常用漢字 4E00-9FFF 為例,輸入

python -c "import sys; sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=1); print(''.join(chr(i) for i in range(0x4E00,0x9FFF+1)))" > D:\word.txt

即可生成到 D 盤下的 word.txt

去除文件中的 BOM、空格、換行並轉換為 UTF-8 格式

Windows 用戶

python -c "t=open('你的原 txt 文件路徑','r',encoding='utf-8-sig').read();t=''.join(sorted(set(t.replace(' ','').replace('\n','').replace('\r',''))));open('D:/word_1.txt','w',encoding='utf-8').write(t)"

Linux 用戶

python3 -c "import sys; t=open('你的原 txt 文件路徑','r',encoding='utf-8-sig').read(); t=''.join(sorted(set(t.replace(' ','').replace('\n','').replace('\r','')))); open('word_1.txt','w',encoding='utf-8').write(t)"

壓縮字體

終端執行

pyftsubset 你的 ttf 字體路徑 --text-file=你的 txt 字符文件路徑 --output-file=D:/output.ttf(生成的文件在 D 盤下)

壓縮成 woff2 字體

終端執行

pyftsubset 你的 ttf 字體路徑 --text-file=你的 txt 字符文件路徑 --flavor=woff2 --output-file=D:/output.woff2 --layout-features='*'(生成的文件在 D 盤下)

教程就到這裡了哦~(˶˃ ᵕ ˂˶) .ᐟ.ᐟ

留言

發表留言

tips: 把 yesreply@ciallovo.top 放到郵件白名單可以接收回復提醒喵~