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

PHP GD 圖形庫實戰:常見繪圖操作完整指南

     編輯:PHP 綜合知識

環境確認

PHP 4.3+ 內建 GD2。檢查是否支援:

if (!function_exists('imagecreate')) {
    die('本伺服器不支援 GD 模組');
}

若不支援:下載 php_gd2.dll、修改 php.ini 啟用 extension=php_gd2.dll、重啟 Web 伺服器。

繪圖四大基本步驟

  1. 建立畫布:$img = imagecreatetruecolor($width, $height);
  2. 分配顏色:$color = imagecolorallocate($img, $r, $g, $b);
  3. 繪製圖形/文字:呼叫各類繪圖函式
  4. 輸出與銷毀:imagepng($img); imagedestroy($img);

核心函式速查表

函式用途關鍵參數
imagecreatetruecolor(w,h)建立真彩色畫布寬、高(像素)
imagecolorallocate(img,r,g,b)分配顏色 IDRGB 0-255 或 0x00-0xFF
imagefill(img,x,y,color)區域填充(連通區域)起始座標、顏色 ID
imageline(img,x1,y1,x2,y2,color)繪製線段起迄座標、顏色
imagestring(img,font,x,y,str,color)內建字體繪文字font=1-5,座標為左上角
imagettftext(img,size,angle,x,y,color,fontfile,text)TrueType 字體繪文字支援中文、旋轉、縮放
imagefilltoborder(img,x,y,border,color)邊界填充遇 border 顏色停止
imagefilledellipse(img,cx,cy,w,h,color)繪製填充橢圓/圓中心座標、寬高、顏色
imagepng(img[,filename])輸出 PNG 影像若無檔名則直接輸出瀏覽器

實戰範例:動態產生驗證碼圖片

<?php
header('Content-Type: image/png');

$width  = 120;
$height = 40;
$img    = imagecreatetruecolor($width, $height);

// 背景與雜訊
$bg      = imagecolorallocate($img, 230, 230, 230);
$noise   = imagecolorallocate($img, 180, 180, 180);
imagefill($img, 0, 0, $bg);
for ($i=0; $i<50; $i++) {
    imagesetpixel($img, rand(0,$width), rand(0,$height), $noise);
}

// 驗證碼文字
$code = substr(md5(rand()), 0, 4);
$_SESSION['captcha'] = $code;
$textColor = imagecolorallocate($img, 0, 0, 0);
$font = 'arial.ttf'; // 需實際字體檔路徑
imagettftext($img, 20, 0, 15, 30, $textColor, $font, $code);

// 輸出
imagepng($img);
imagedestroy($img);
?>

進階提示

  • 記憶體管理:務必呼叫 imagedestroy() 釋放資源
  • 字體路徑:imagettftext 需給予完整 .ttf 檔路徑
  • 輸出格式:另支援 imagejpeg()、imagewbmp()、imagegif()(需 GD 2.0.28+)
  • 座標系:左上角為 (0,0),X 向右、Y 向下

掌握上述核心函式,即可實現圖表產生、圖片水印、驗證碼、縮圖等常見需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved