14.5. php 的 ImageTTFText() 經常抓錯字?

patched by: jerry

    --- 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)++;
            }

中文測試檔:

    <?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);
    ?>

以上是 patch source 的做法,或是使用 unicode 也可以讓中文正常的顯示,以下就是 big5 轉 unicode 的做法。

    <?php
    function big52uni($text){
       $rtext="";
       $table=file("big5-uni.txt");
       $max=strlen($text);
       for($i=0;$i<$max;$i++){
          $h=ord($text[$i]);
          $l=ord($text[$i+1]);
          if($h>=160 && $i<$max-1){
             $uni=ereg_replace(".{5}([0-9]*)[\xd|\xa]","&#\\1;",$table[191*($h-129)+($l-64)]);
             $rtext.=$uni;
             $i++;
          }else{
             $rtext.=$text[$i];
          }
       }
       return $rtext;
    }
    ?>

用法的範例如下:

    <?php
    Header("Content-type: image/gif");
    $im = imagecreate(400,30);
    $black = ImageColorAllocate($im, 0,0,0);
    $white = ImageColorAllocate($im, 255,255,255);
    // 以下是輸出標楷體中文,至於中文字形檔位置請根據自己電腦做修改
    // 還有big52uni這個function在上面有,請自行複製過去用
    // 備註:您必需裝GD及FreeType的套件才能輸出TTF字型 
    ImageTTFText($im, 20, 0, 10, 20, $white, "/usr/X11R6/lib/X11/fonts/TrueType/moe_kai.ttf", big52uni("Test中文測試"));
    ImageGif($im);
    ImageDestroy($im);
    ?>

WWW: http://www.php.net/