當前位置: 首頁> 最新文章列表> 在CAPTCHA 驗證碼中使用imageantialias() 提升可讀性

在CAPTCHA 驗證碼中使用imageantialias() 提升可讀性

M66 2025-05-23

在製作CAPTCHA 驗證碼時,如何保證驗證碼既能防止機器自動識別,又能讓用戶輕鬆識別,是一個重要的技術難點。 PHP 提供了豐富的圖像處理函數,其中imageantialias()可以有效地提升圖像的抗鋸齒效果,從而讓驗證碼中的文字或圖形邊緣更加平滑,增強可讀性。

本文將結合PHP 的GD 庫演示如何在生成CAPTCHA 驗證碼時使用imageantialias()函數來提升驗證碼的視覺效果。


什麼是imageantialias()?

imageantialias()是PHP GD 庫中的一個函數,用於開啟或關閉圖像的抗鋸齒效果。鋸齒是因為圖像邊緣出現不平滑的階梯狀像素邊界,抗鋸齒通過對邊緣像素進行平滑處理,使邊緣看起來更圓滑。

函數原型如下:

 bool imageantialias ( resource $image , bool $enable )
  • $image :圖像資源句柄

  • $enable :開啟或關閉抗鋸齒效果, true為開啟, false為關閉


在CAPTCHA 驗證碼中使用imageantialias()

1. 創建驗證碼圖片

我們先創建一張基礎的驗證碼圖片:

 <?php
// 創建一張 150x50 的空白圖像
$image = imagecreatetruecolor(150, 50);

// 分配顏色
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// 填充背景為白色
imagefilledrectangle($image, 0, 0, 150, 50, $white);

2. 啟用抗鋸齒

啟用抗鋸齒後,繪製的線條和文字邊緣會更平滑:

 // 開啟抗鋸齒
imageantialias($image, true);

3. 繪製干擾線條

在驗證碼中加入乾擾線條,防止簡單OCR 識別:

 for ($i = 0; $i < 5; $i++) {
    $line_color = imagecolorallocate($image, rand(100, 150), rand(100, 150), rand(100, 150));
    imageline($image, rand(0, 150), rand(0, 50), rand(0, 150), rand(0, 50), $line_color);
}

4. 添加驗證碼文字

這裡使用imagettftext()函數繪製文字,利用抗鋸齒使文字更清晰:

 $font = __DIR__ . '/fonts/arial.ttf'; // 請確保字體路徑正確
$code = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 5);

for ($i = 0; $i < strlen($code); $i++) {
    $text_color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
    imagettftext(
        $image,
        20,
        rand(-15, 15),
        20 + $i * 25,
        rand(30, 40),
        $text_color,
        $font,
        $code[$i]
    );
}

5. 輸出驗證碼圖片並釋放資源

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>

注意事項

  • imageantialias()只對繪製的線條和形狀生效, imagettftext()渲染的字體本身已經內置了抗鋸齒效果。

  • 開啟抗鋸齒可能會稍微增加CPU 負擔,但提升的圖像質量通常值得。

  • 確保字體文件存在,路徑正確,否則文字不會正常顯示。


完整示例代碼

<?php
// 創建圖像
$image = imagecreatetruecolor(150, 50);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 150, 50, $white);

// 啟用抗鋸齒
imageantialias($image, true);

// 繪製干擾線條
for ($i = 0; $i < 5; $i++) {
    $line_color = imagecolorallocate($image, rand(100, 150), rand(100, 150), rand(100, 150));
    imageline($image, rand(0, 150), rand(0, 50), rand(0, 150), rand(0, 50), $line_color);
}

// 驗證碼文字
$font = __DIR__ . '/fonts/arial.ttf';
$code = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 5);

for ($i = 0; $i < strlen($code); $i++) {
    $text_color = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
    imagettftext($image, 20, rand(-15, 15), 20 + $i * 25, rand(30, 40), $text_color, $font, $code[$i]);
}

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>

通過以上示例,你可以清晰地看到imageantialias()對圖像中線條邊緣的平滑提升,從而提高CAPTCHA 驗證碼的整體可讀性。結合干擾線和變形文字,可以有效提升驗證碼的安全性和用戶體驗。


如果你需要訪問相關資源或API,請注意將URL 域名替換為m66.net ,例如: