當前位置: 首頁> 最新文章列表> 多邊形繪圖結合GD 庫生成驗證碼圖像

多邊形繪圖結合GD 庫生成驗證碼圖像

M66 2025-05-29

在PHP 中,GD 庫提供了強大的圖像處理功能,可以繪製各種圖形,包括多邊形。如果你希望生成一個帶有隨機多邊形圖案的驗證碼,提高驗證碼的防破解性, imageopenpolygon函數將非常有用。

本文將詳細介紹如何使用imageopenpolygon與GD 庫繪製多邊形,並生成一張簡單的驗證碼圖片。

環境要求

  • PHP 7.0 及以上

  • 已安裝並啟用GD 擴展(可以通過phpinfo()查看是否啟用)

什麼是imageopenpolygon

imageopenpolygon是GD 庫提供的函數之一,用來在一張圖像上繪製開放式的多邊形(即線條首尾不連接)。與imagepolygon (繪製閉合多邊形)不同, imageopenpolygon更適合需要畫開放曲線的場景,比如驗證碼的干擾線條等。

函數定義如下:

 bool imageopenpolygon(GdImage $image, array $points, int $num_points, int $color)
  • $image :要繪製的圖像資源。

  • $points :包含點坐標的數組[x0, y0, x1, y1, x2, y2, ...]

  • $num_points :頂點數量。

  • $color :線條顏色。

示例:繪製多邊形驗證碼

下面是一個完整的示例,演示如何生成一個含有隨機多邊形的驗證碼圖像:

 <?php
// 設置內容類型為圖片
header('Content-Type: image/png');

// 創建畫布
$width = 200;
$height = 70;
$image = imagecreatetruecolor($width, $height);

// 顏色設置
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
$textColor = imagecolorallocate($image, 0, 0, 0);             // 黑色字體
$polygonColor = imagecolorallocate($image, 100, 100, 255);    // 藍色多邊形

// 填充背景
imagefill($image, 0, 0, $backgroundColor);

// 生成隨機驗證碼文本
$characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$captchaText = '';
for ($i = 0; $i < 5; $i++) {
    $captchaText .= $characters[rand(0, strlen($characters) - 1)];
}

// 寫入驗證碼文本
$fontSize = 5; // 內置字體大小
$x = ($width - imagefontwidth($fontSize) * strlen($captchaText)) / 2;
$y = ($height - imagefontheight($fontSize)) / 2;
imagestring($image, $fontSize, $x, $y, $captchaText, $textColor);

// 隨機繪製多個開放多邊形
for ($i = 0; $i < 3; $i++) {
    $points = [];
    $numPoints = rand(3, 6); // 三角形到六邊形
    for ($j = 0; $j < $numPoints; $j++) {
        $points[] = rand(0, $width);
        $points[] = rand(0, $height);
    }
    imageopenpolygon($image, $points, $numPoints, $polygonColor);
}

// 輸出圖像
imagepng($image);

// 銷毀資源
imagedestroy($image);
?>

運行效果

運行上面的PHP 文件時,你會看到一個背景是白色、中央有一組隨機字母數字的驗證碼,周圍有若干隨機繪製的藍色開放式多邊形,增加了圖像的干擾性。

注意事項

  1. GD 擴展必須啟用。如果未啟用,可通過安裝命令如apt install php-gd或編輯php.ini來啟用。

  2. 驗證碼複雜性提升:可以通過增加多邊形數量、修改顏色和圖形大小,使驗證碼更加複雜,防止自動識別。

  3. 安全輸出:生成圖像前不要有任何HTML 輸出,否則圖像文件會被破壞。

拓展應用

如果希望讓驗證碼更加個性化,比如添加彎曲的文字、旋轉效果、背景噪點,可以使用更高級的庫如Captcha Builder for PHP進行開發。