首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP GD 繪圖實作中文輸出:點陣字庫 (chs16.fon) 解析與描點法繪製

     編輯:PHP 相關知識

背景問題

PHP imagestring() 僅支援單位元組字元,無法正確輸出中文 (GB2312/UTF-8)。iconv 擴充不一定可用,且主機商可能禁用 dl()。

解決方案:點陣字庫 + 描點法

  1. 使用 Windows 內建 chs16.fon (GB2312 16x16 點陣字庫),每字 32 位元組 (16行 x 2位元組)。
  2. 機內碼 (雙高位元組) 轉區位碼:區位碼 = 機內碼 - 0xA0A0。
  3. 檔案偏移量:offset = (94 * (區-1) + (位-1)) * 32。
  4. 讀取 32 位元組,雙重迴圈逐點繪製:imagesetpixel($im, $x + 8*$byte, $y, $color)。

核心函數 draw()

function draw($image, $string, $color) {
    $fp = fopen('chs16.fon', 'rb');
    while ($string) {
        $qh = ord(substr($string, 0, 1)) - 0xA0; // 區
        $wh = ord(substr($string, 1, 1)) - 0xA0; // 位
        $offset = (94 * ($qh - 1) + ($wh - 1)) * 32;
        fseek($fp, $offset, SEEK_SET);
        $buffer = fread($fp, 32); // 32 位元組

        for ($row = 0; $row < 16; $row++) {
            for ($byte = 0; $byte < 2; $byte++) {
                $bits = ord($buffer[$row * 2 + $byte]);
                for ($col = 0; $col < 8; $col++) {
                    if ($bits & (0x80 >> $col)) {
                        imagesetpixel($image, $col + 8 * $byte, $row, $color);
                    }
                }
            }
        }
        $string = substr($string, 2); // 處理下一個中文字
    }
    fclose($fp);
}

使用範例

<?php
header('Content-type: image/png');
$im = imagecreate(400, 100);
$bg = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);
draw($im, '中文測試', $red);
imagepng($im);
imagedestroy($im);
?>

輸出 PNG 圖片,黑底紅字顯示中文。字庫檔需置於腳本同目錄 (Linux 注意大小寫)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved