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

PHP GD 實現中文漢字驗證碼:繪製干擾線、點與 TTF 文字

     編輯:PHP 綜合知識

完整生成流程

// 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 驗證
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved