Contributed by jerry <[email protected]>
Last Update: 2003年 4月29日 周二 19時43分15秒 CST
在安裝 www/mod_php4 時必須選擇 GD library support 及 freetype 的套件才能進行下面的步驟。
目前常見的有三種做法,一種是 patch gdttf.c, 一種是使用 iconv support 來將編碼轉成 UCS-2 , 還有一種就是直接使用 chinese/hc 的資料庫。
這邊是第一種做法,patch gdttf.c 讓 PHP 不會抓錯字。
--- gdttf.c.orig Mon Oct 16 21:55:47 2000
+++ gdttf.c Sun Dec 31 18:00:34 2000
@@ -654,7 +654,7 @@
TT_BBox **bbox,
char **next)
{
- int pc, ch, len;
+ int pc, ch, len, ch2;
int row, col;
int x2, y2; /* char start pos in pixels */
int x3, y3; /* current pixel pos */
@@ -687,6 +687,8 @@
(*next)++;
if (ch >= 161 /* first code of JIS-8 pair */
&& **next) { /* don't advance past '\0' */
+ ch2 = (**next) & 255;
+ if(ch2 >= 161) ch++; /* Big5 ttf patch */
ch = (ch * 256) + **next;
(*next)++;
}
由於已經處理過 gdttf.c,在這邊就可以直接使用中文編碼的字。
<?php
Header ("Content-type: image/gif");
$im = imagecreate (400, 30);
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
ImageTTFText ($im, 20, 0, 10, 20, $white,
"/usr/X11R6/lib/X11/fonts/TrueType/moe_kai.ttf", "這是中文測試 許功蓋 ");
ImagePng ($im);
ImageDestroy ($im);
?>
第二種是使用 unicode 讓中文正常的顯示, 以下就是 big5 轉 unicode 的做法, 在這邊提供一個小函式來自動判斷為英文還是中文, 英文的部分不需要轉碼,只有中文才需要。
<?php
/* need iconv module */
function big52uni($text) {
$rtext="";
$max=strlen($text);
for($i=0;$i<$max;$i++){
$h=ord($text[$i]);
if($h>=160 && $i<$max-1){
$rtext.="&#".base_convert(bin2hex(iconv("big5","ucs-2",
substr($text,$i,2))),16,10).";";
$i++;
}else{
$rtext.=$text[$i];
}
}
return $rtext;
}
?>
用法的範例如下,在 ImageTTFText 必須指定系統上的字型, 以下是安裝 chinese/arphicttf 來使用文鼎PL上海宋,所以必須根據自己的安裝的字型作修改, 然後搭配上面的 big52uni 這個函式:
<?php
Header("Content-type: image/gif");
$im = imagecreate(400,30);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
ImageTTFText($im, 20, 0, 10, 20, $white,
"/usr/local/share/fonts/TrueType/bsmi00lp.ttf",
big52uni("Test中文測試"));
ImageGif($im);
ImageDestroy($im);
?>
WWW: http://www.php.net/