論壇簽名檔、部落格側邊欄、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() | 釋放圖片佔用的記憶體 |
__DIR__.'/fonts/Tahoma.ttf'imagecolortransparent($img, $bgColor) 或使用 imagesavealpha($img, true) 配合 alpha 通道fastcgi_cache 快取 PHP 輸出$_SERVER['HTTP_X_FORWARDED_FOR'] 或 $_SERVER['HTTP_CLIENT_IP']