完整生成流程
// 1. 創建畫布
$image = imagecreatetruecolor(200, 60);
$background = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background);
// 2. 干擾點
for ($i = 0; $i < 300; $i++) {
$color = imagecolorallocate($image, rand(150,240), rand(150,240), rand(150,240));
imagesetpixel($image, rand(10,190), rand(5,55), $color);
}
// 3. 干擾線
for ($i = 0; $i < 5; $i++) { // 橫線
$color = imagecolorallocate($image, rand(50,150), rand(50,150), rand(50,150));
imageline($image, 0, ($i+1)*12, 300, ($i+1)*12, $color);
}
for ($i = 0; $i < 30; $i++) { // 豎線
$color = imagecolorallocate($image, rand(50,150), rand(50,150), rand(50,150));
imageline($image, ($i+1)*10, 0, ($i+1)*10, 60, $color);
}
// 4. 繪製漢字
$text = array('栀', '子', '花', '開');
for ($i = 0; $i < 4; $i++) {
$color = imagecolorallocate($image, rand(20,100), rand(20,100), rand(20,100));
$x = $i * 50 + 10;
$y = rand(40, 60);
// 必須使用支援中文的 TTF 字體
imagettftext($image, 30, rand(20,50), $x, $y, $color, "/Library/Fonts/華文仿宋.ttf", $text[$i]);
}
// 5. 輸出
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
關鍵提示
- 字體文件必須支援中文(如華文仿宋、微軟雅黑)
- 源文件編碼須為 UTF-8,GBK 需
iconv 轉換
- 實際項目中應從漢字庫隨機抽取,並存入 Session 驗證