Java 通过指定的ttf字体库,提取特定文字
前言
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.ttfsfnttool.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 formatmsyh.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.ttfString 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();}運行預覽圖
點擊下方卡片/微信搜索,關注公眾號“天宇文創意樂派”(ID:gh_cc865e4c536b)
聽說點贊和關注本號的都找到漂亮的小姐姐了喲且年后必入百萬呀!!
提取特定文字ttf工具類.zip
總結
以上是生活随笔為你收集整理的Java 通过指定的ttf字体库,提取特定文字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS之获取指定位置Unicode的cha
- 下一篇: 前端开发必须要了解的CSS原理