萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 繪製驗證碼完整教學:畫布、干擾點、干擾線、輸出 PNG

完整程式碼

<?php
/**
 * PHP 產生驗證碼圖片
 * @param int $width      畫布寬度
 * @param int $height     畫布高度
 * @param int $vcodelen   驗證碼長度
 * @param int $pointnum   干擾像素點數量
 * @param int $linenum    干擾線條數量
 */
$width   = 100;
$height  = 30;
$vcodelen = 4;
$pointnum = 200;
$linenum  = 3;

// 1. 建立真彩色畫布
$image = imagecreatetruecolor($width, $height);

// 2. 分配背景色(白色)並填滿
$bgcolor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);

// 3. 繪製驗證碼字元
$charset = 'abcdefghijklmnopqrstuvwxyz0123456789';
for ($i = 0; $i < $vcodelen; $i++) {
    $fontsize  = 5; // imagestring 只支援 1-5
    $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    $char      = $charset[rand(0, strlen($charset) - 1)];
    $x         = ($i * $width / 4) + rand(5, 15);
    $y         = rand(5, 10);
    imagestring($image, $fontsize, $x, $y, $char, $fontcolor);
    // 若需更大字體,請用 imagettftext() 需 .ttf 字體檔
}

// 4. 干擾像素點
for ($i = 0; $i < $pointnum; $i++) {
    $color = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}

// 5. 干擾線條
for ($i = 0; $i < $linenum; $i++) {
    $color = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}

// 6. 輸出 PNG 並釋放資源
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>

關鍵函式說明

函式用途
imagecreatetruecolor()建立真彩色圖片資源(支援 24-bit)
imagecolorallocate()分配顏色識別碼(R,G,B 0-255)
imagefill()從座標起點填滿顏色
imagestring()繪製水平字串(內建 5x7 字體,大小 1-5)
imagettftext()繪製 TrueType 字體文字(需字體檔,支援任意大小/旋轉)
imagesetpixel()畫單一像素點
imageline()畫直線
imagepng()輸出 PNG 格式到瀏覽器或檔案
imagedestroy()釋放圖片資源佔用的記憶體

進階建議

  • Session 儲存:產生驗證碼後,將字串存入 $_SESSION['captcha'],驗證時比對(注意大小寫)。
  • 字體多樣化:準備多個 .ttf 字體檔,隨機選擇並隨機旋轉角度(imagettftext 第 3 參數)。
  • 干擾曲線:用 imagebezier 或自行實作貝茲曲線,比直線更難被 OCR 識別。
  • 效能:高併發時,考慮預先生成驗證碼圖片池,或使用專門驗證碼服務(如 Google reCAPTCHA、hCaptcha)。
copyright © 萬盛學電腦網 all rights reserved