PHP imagestring() 僅支援單位元組字元,無法正確輸出中文 (GB2312/UTF-8)。iconv 擴充不一定可用,且主機商可能禁用 dl()。
chs16.fon (GB2312 16x16 點陣字庫),每字 32 位元組 (16行 x 2位元組)。區位碼 = 機內碼 - 0xA0A0。offset = (94 * (區-1) + (位-1)) * 32。imagesetpixel($im, $x + 8*$byte, $y, $color)。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 注意大小寫)。