前言
web开发中常常须要用到各类字体,可是网上下载的TTF字体文件最小也有好几兆,要是须要用到几种字体,那简直惨不忍睹。
一般状况下,咱们会用BMFont代替TTF字体,BMFont也有着不少的优点,可是缺点也很明显,每次修改都要美工的配合,并且不支持字号改变(不考虑缩放)。
那么有没有办法能把TTF字体文件变小点呢?答案是确定的,除了用FontCreator那种累死人不偿命的东西以外,这里介绍一个简单实用的工具。
介绍
sfnttool 是谷歌开源项目 sfntly 内置的工具,他的做用是从一个字体文件中提取指定的文字,导出的字体中将只包含你须要的文字。
使用
1. 确保你的电脑已经安装了Java环境(能运行Java命令)。this
2. 命令行进入到sfnttool所在目录下。(一个小技巧,在当前文件夹里按住Shift再右键,里面有个“在此处打开命令行”。)google
3. 输入下面的命令便可:
java -jar sfnttool.jar -s '这是一段测试文字' msyh.ttf msyh_simplify.ttf
sfnttool.jar说明以下:
java -jar sfnttool.jar -hsubset [-?|-h|-help] [-b] [-s string] fontfile outfileprototype font subsetter -?,-help print this help information -s,-string string to subset -b,-bench benchmark (run 10000 iterations) -h,-hints strip hints -w,-woff output woff format -e,-eot output eot format -x,-mtx enable microtype express compression for eot format
msyh.ttf :字体库文件
msyh_simplify.ttf:目标文件/输出文件
Java coding
private static void process() throws Exception{
String content = "猜你喜欢 主编力荐 限时 精选 品质 热门推荐 新书 包括完本 全部 连载";
content = content.replaceAll("\\s*",""); //文字内容去除空格字符
File toolFile = ResourceUtils.getFile("classpath:lib/sfnttool.jar"); //这种方法在linux下无法工作
File fontFile = ResourceUtils.getFile("classpath:font/fzxbs_gbk.ttf"); //这种方法在linux下无法工作
//jar文件的绝对路径
String jarAbsolutePath = toolFile.getAbsolutePath();
//字体库文件的绝对路径
String fontAbsolutePath = fontFile.getAbsolutePath();
//目标目录
String target = "./base-font.ttf";
//java -jar sfnttool.jar -s '这是一段测试文字' msyh.ttf msyh_simplify.ttf
String params = " java -jar %s -s '%s' %s %s ";
String command = String.format(params, jarAbsolutePath, content, fontAbsolutePath, target);
log.info("执行命令 command = {} ", command);
Process exec ;
try {
exec = Runtime.getRuntime().exec(command);
int i = exec.waitFor(); //当前线程等待 0表示正常终止
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
文件对应目录截图
文件输出截图
在推荐一个GUI Java coding 文件对应截图 就是SfntToolGUI.jar
private static void useGUI() throws Exception{
File guiFile = ResourceUtils.getFile("classpath:lib/SfntToolGUI.jar"); //这种方法在linux下无法工作
//jar文件的绝对路径
String jarAbsolutePath = guiFile.getAbsolutePath();
String command = " java -jar ".concat(jarAbsolutePath);
Process exec ;
try {
exec = Runtime.getRuntime().exec(command);
int i = exec.waitFor(); //当前线程等待 0表示正常终止
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
//process();
useGUI();
}
运行预览图