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

PHP GD 繪圖實作:動態生成顯示訪客 IP 的圖片

     編輯:PHP 相關知識

應用場景

論壇簽名檔、部落格側邊欄、API 回應圖片等需動態顯示訪客 IP 的場景,可透過 PHP GD 庫即時生成 PNG 圖片輸出。

完整代碼範例

<?php
// 設定輸出為 PNG 圖片
header("Content-type: image/png");

// 建立 180x50 像素畫布
$img = imagecreatetruecolor(180, 50);

// 取得訪客 IP
$ip = $_SERVER['REMOTE_ADDR'];

// 分配顏色 (RGB)
$bgColor   = imagecolorallocate($img, 0x2C, 0x6D, 0xAF); // 深藍背景
$shadow    = imagecolorallocate($img, 250, 0, 0);        // 紅色陰影
$textColor = imagecolorallocate($img, 0xFF, 0xFF, 0xFF); // 白色文字

// 字型路徑 (Windows 範例,Linux 需調整為 /usr/share/fonts/... )
$font = 'c:/windows/fonts/Tahoma.ttf';

// 繪製陰影文字 (偏移 3px)
imagettftext($img, 10, 0, 78, 30, $shadow, $font, $ip);

// 繪製主文字
imagettftext($img, 10, 0, 25, 28, $textColor, $font, "Your IP is {$ip}");

// 輸出並銷毀資源
imagepng($img);
imagedestroy($img);
?>

關鍵函式說明

函式用途
imagecreatetruecolor()建立真彩色圖片 (優於 imagecreate())
imagecolorallocate()分配 RGB 顏色識別碼
imagettftext()使用 TrueType 字型繪製反鋸齒文字
imagepng()輸出 PNG 格式至瀏覽器或檔案
imagedestroy()釋放圖片佔用的記憶體

常見問題與優化

  • 字型路徑跨平台:Windows 用絕對路徑,Linux 建議將 .ttf 檔放專案目錄並用相對路徑 __DIR__.'/fonts/Tahoma.ttf'
  • 透明背景:若需透明背景,建立畫布後呼叫 imagecolortransparent($img, $bgColor) 或使用 imagesavealpha($img, true) 配合 alpha 通道
  • 效能:高併發場景下,建議快取生成的圖片或使用 Nginx fastcgi_cache 快取 PHP 輸出
  • IP 取得:反向代理/負載均衡環境下,應讀取 $_SERVER['HTTP_X_FORWARDED_FOR'] 或 $_SERVER['HTTP_CLIENT_IP']
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved