webfont自定义字体的实现方案

时间:2023-03-08 18:41:26

对于做Web前端的人来说,现在不知道webfont为何物似乎显得有点low了。webfont固然可爱,但似乎仍只可远观,不可亵玩。原因就在于中文字体库体积庞大,远比26个字母来的复杂。于是有同学就说了,为何不制作一个精简的字库,按需订制就可以了。正解,下面的就介绍下制作方法:

工具:提供font字体的网站(比如:http://sampler.linotype.com/sam/sam?ID=1390633&text=狠&sizex=4000&sizey=4000&fontsize=3000,ID对应字体,text对应字,其它定义字体大小),fontforge字体编辑器,wget下载工具,PHP运行环境。

1、首先确认你需要哪些字,将这些字依次填入txt文档中,并以utf8格式保存;

2、下载安装wget工具、PHP运行环境。在cmd下运行php文件,根据txt文件中的字自动下载字体图片,并以中文unicode给图片命名,保存在指定文件夹。

$file_path = "fan.txt";//txt格式默认用utf8格式,否则转换
$str=file_get_contents($file_path);
$encode= mb_detect_encoding($str, array('GB2312','GBK','UTF-8'),true);
if($encode=="GB2312")
{
$str = iconv("GB2312","UTF-8",$str);
}
else if($encode=="GBK")
{
$str = iconv("GBK","UTF-8",$str);
}
else if($encode=="EUC-CN")
{
$str = iconv("GBK","UTF-8",$str);
}
else//CP936
{
//$str = iconv("GB2312","UTF-8",$str);
$str = mb_convert_encoding($str, 'UTF-8', 'GBK');//把GBK编码转化为 UTF-8编码
}
$arr=array();
for($i=0;$i<mb_strlen($str,'utf8');$i++){
$arr[$i]=mb_substr($str,$i,1,'utf8');
}
$imgpath = './08/';//图片保存的文件夹
foreach($arr as $key=>$value){
$code=unicode_encode($value);
if(file_exists($imgpath.$code.'.png')){
echo $imgpath.$mycode.'.png is already exist';continue;
}
$value=urlencode($value);
$url="http://sampler.linotype.com/sam/sam?ID=1390633^&text=".$value."^&sizex=4000^&sizey=4000^&fontsize=3000";
$command="d:/wget/wget -T 25 -t 0 -O ".$imgpath.$code.".png ".$url;//d:/wget为wget的执行文件路径
exec($command);
}
//将内容进行UNICODE编码,编码后的内容格式:56fe
function unicode_encode($name)
{
$name = iconv('UTF-8', 'UCS-2', $name);
$len = strlen($name);
$str = '';
for ($i = 0; $i < $len - 1; $i = $i + 2)
{
$c = $name[$i];
$c2 = $name[$i + 1];
if (ord($c) > 0)
{ // 两个字节的文字
$c=base_convert(ord($c), 10, 16);
$c2=base_convert(ord($c2), 10, 16);
if(strlen($c)<2)$c="0".$c;
if(strlen($c2)<2)$c2="0".$c2;
$str .=$c.$c2;
}
else
{
$str .= $c2;
}
}
return $str;
}

3、安装fontforge,该软件支持python,运行python脚本自动导入指定目录下的字体图片(根据文件名对应汉字),然后导出生成字体文件,该文件即为简化后的字体库。此python脚本一次导入50张图,字数多的需要多次导入。

import os,fontforge;
imgsPath = "D:/phpstudy/www/img";
imgs = os.listdir(imgsPath);
font = fontforge.activeFont();
i = 0;
for index in xrange(len(imgs)):
fontforge.logWarning("index:"+str(index));imgName = imgs[index][:-4];fontforge.logWarning("imgName:"+imgName)
glyph=font.createChar(int(imgName,16),"uni"+imgName);
layer=glyph.foreground;
if layer.isEmpty():
try:
glyph.importOutlines(imgsPath+"/"+imgs[index]);
except:
fontforge.logWarning(str(index)+"/"+str(len(imgs))+":"+imgsPath+"/"+imgs[index]+"is error");
continue;
else:
glyph.autoTrace();glyph.simplify();glyph.activeLayer=0;glyph.clear();i=i+1;
fontforge.logWarning(str(index)+"/"+str(len(imgs))+":"+imgsPath+"/"+imgs[index]+"is OK"+str(i))
if i==50:
break;
else:
continue;