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

PHP GD 圖形處理入門教學:從建立畫布到驗證碼 12 步完整實作

     編輯:PHP 相關知識

前言

GD 擴充套件是 PHP 內建的圖形處理引擎,掌握其核心 API 能快速實作驗證碼、圖表、浮水印、縮圖等功能。本文整理 12 個遞進式範例,從建立畫布到完整驗證碼程式,適合初學者循序漸進掌握 GD 核心概念。

範例 1:建立簡單畫布並輸出 PNG

$width = 200; $height = 200;
$img = imagecreatetruecolor($width, $height) or die("不支援 GD");
imagepng($img);
imagedestroy($img);

重點:imagecreatetruecolor 建立真彩畫布 (24-bit);imagepng 輸出二進位;imagedestroy 釋放記憶體。

範例 2:設定背景顏色

$img = imagecreatetruecolor(200, 200);
$bg = imagecolorallocate($img, 255, 0, 0); // RGB 紅
imagefill($img, 0, 0, $bg);
imagepng($img); imagedestroy($img);

重點:imagecolorallocate 分配調色盤索引;imagefill 從 (0,0) 填滿。

範例 3:繪製直線

$img = imagecreatetruecolor(200, 300);
$white = imagecolorallocate($img, 255,255,255);
imageline($img, 0, 40, 200, 40, $white);   // 上橫線
imageline($img, 0, 260, 200, 260, $white); // 下橫線
imagepng($img); imagedestroy($img);

重點:imageline($im, x1, y1, x2, y2, $color) 座標原點在左上角。

範例 4:內建字型輸出英文

$img = imagecreatetruecolor(200, 300);
$white = imagecolorallocate($img, 255,255,255);
imageline($img, 0, 40, 200, 40, $white);
imageline($img, 0, 260, 200, 260, $white);
imagestring($img, 5, 0, 60, "it's time to learn php!", $white); // 字型 1-5
imagepng($img); imagedestroy($img);

重點:imagestring 僅支援 Latin-1,字型 1-5 為內建點陣字體。

範例 5:TrueType 字型輸出中文 (垂直/水平)

$img = imagecreatetruecolor(200, 300);
$white = imagecolorallocate($img, 255,255,255);
$font  = "c:/windows/fonts/simli.ttf"; // 隸書

// 十六進位 UTF-8 組字 (舊式寫法)
$c1 = chr(0xe8).chr(0xa5).chr(0xbf); // 西
$c2 = chr(0xe6).chr(0xb8).chr(0xb8); // 遊
$c3 = chr(0xe8).chr(0xae).chr(0xb0); // 記

imagettftext($img, 30, 0, 10, 80, $white, $font, $c1);
imagettftext($img, 30, 0, 10, 120, $white, $font, $c2);
imagettftext($img, 30, 0, 10, 160, $white, $font, $c3);

// 現代寫法:直接用 UTF-8 字串 (PHP 檔案需儲存為 UTF-8)
imagettftext($img, 15, 0, 90, 254, $white, $font, "吳承恩著");

重點:imagettftext 需 FreeType 支援;座標 x,y 為基線左下角;角度逆時針度數。

範例 6:讀取現有圖片 (JPEG)

$img = imagecreatefromjpeg("tower.jpg");
imagejpeg($img);
imagedestroy($img);

同類函式:imagecreatefromgif/png/webp/bmp。

範例 7:取得圖片寬高

$img = imagecreatefromjpeg("tower.jpg");
$x = imagesx($img); $y = imagesy($img);
echo "寬:$x px, 高:$y px";
imagedestroy($img);

範例 8:getimagesize() 完整資訊

$info = getimagesize("tower.jpg");
// $info[0]=寬, [1]=高, [2]=類型常數(1=GIF,2=JPEG,3=PNG...), [3]=HTML屬性字串
// $info['bits'], ['channels'], ['mime']
for ($i=0; $i<4; $i++) echo $info[$i]."<br/>";

範例 9:為上傳圖片加浮水印

$dst = imagecreatefromjpeg("photo.jpg");
$watermark = imagecreatefrompng("logo.png"); // 含透明通道
$dstW = imagesx($dst); $dstH = imagesy($dst);
$wmW = imagesx($watermark); $wmH = imagesy($watermark);
// 右下角留 10px 邊距
imagecopy($dst, $watermark, $dstW-$wmW-10, $dstH-$wmH-10, 0,0, $wmW,$wmH);
imagejpeg($dst, "photo_wm.jpg");
imagedestroy($dst); imagedestroy($watermark);

範例 10:產生縮圖 (等比)

$src = imagecreatefromjpeg("photo.jpg");
$srcW = imagesx($src); $srcH = imagesy($src);
$maxW = 200; $maxH = 200;
$ratio = min($maxW/$srcW, $maxH/$srcH);
$newW = (int)($srcW*$ratio); $newH = (int)($srcH*$ratio);
$thumb = imagecreatetruecolor($newW, $newH);
imagecopyresampled($thumb, $src, 0,0,0,0, $newW,$newH, $srcW,$srcH);
imagejpeg($thumb, "thumb.jpg", 90);
imagedestroy($src); imagedestroy($thumb);

範例 11:imagecopyresampled() 高畫質縮放

已在範例 10 示範。關鍵差異:

  • imagecopyresized:最近鄰插值,鋸齒明顯、速度快。
  • imagecopyresampled:雙三次插值,平滑銳利、速度稍慢,生產環境首選。

範例 12:完整驗證碼程式 (含干擾線、Session)

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

$im = imagecreatetruecolor(100, 36);
$bg = imagecolorallocate($im, 240,240,240);
$textColor = imagecolorallocate($im, 0,0,0);
$noise = imagecolorallocate($im, 180,180,180);
imagefill($im, 0, 0, $bg);

// 干擾線
for($i=0;$i<6;$i++) imageline($im, rand(0,100), rand(0,36), rand(0,100), rand(0,36), $noise);
// 干擾點
for($i=0;$i<80;$i++) imagesetpixel($im, rand(0,100), rand(0,36), $noise);

// 4 碼驗證碼
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for($i=0;$i<4;$i++) $code .= $chars[rand(0, strlen($chars)-1)];
$_SESSION['captcha'] = strtoupper($code);

// 逐字繪製 (隨機旋轉/位移)
$x = 10;
for($i=0;$i<4;$i++) {
    imagettftext($im, 20, rand(-10,10), $x, rand(24,30), $textColor,
                 __DIR__.'/fonts/DejaVuSans.ttf', $code[$i]);
    $x += 20;
}
imagepng($im);
imagedestroy($im);

GD 核心函式速查表

分類函式用途
建立畫布imagecreatetruecolor(w,h)真彩畫布 (建議)
imagecreate(w,h)調色盤畫布 (256 色,舊版相容)
imagecreatefrom* (jpeg/png/gif/webp/bmp)從檔案/字串建立資源
顏色imagecolorallocate(im, r,g,b)分配不透明色
imagecolorallocatealpha(im, r,g,b, alpha)分配半透明色 (0=不透明, 127=全透明)
imagecolortransparent(im, color)設定透明色索引
繪圖imageline(im, x1,y1, x2,y2, c)直線
imagerectangle/ellipse/arc矩形/橢圓/弧
imagefilled*填滿版本
imagettftext(im, size, angle, x, y, c, font, text)TrueType 文字
複製/縮放imagecopy(dst, src, dx,dy, sx,sy, sw,sh)像素級複製
imagecopyresized(...)縮放複製 (低畫質)
imagecopyresampled(...)縮放複製 (高畫質)
輸出imagejpeg/png/gif/webp(im, file?, quality?)輸出檔案/瀏覽器
imagepng(im, file, compress_level 0-9)PNG 壓縮等級
imagedestroy(im)釋放資源

常見坑點與解法

  1. 中文亂碼:PHP 檔案必須存為 UTF-8 無 BOM,字體需支援中文 (如 Noto Sans TC)。
  2. 字體找不到:使用絕對路徑 __DIR__.'/fonts/xxx.ttf',確認 freetype 編譯支援。
  3. 記憶體爆炸:大圖處理前 ini_set('memory_limit', '256M'),處理完立即 imagedestroy()。
  4. 輸出前有空白:header() 前不能有任何輸出,檢查 ?> 後是否有換行。

小結

這 12 個範例涵蓋 GD 從建立、繪圖、文字、讀檔、屬性、浮水印、縮圖、驗證碼的完整入門路徑。建議實際動手執行每個範例,觀察輸出結果,再嘗試修改參數 (顏色、座標、字體、尺寸) 體會差異。掌握核心 API 後,即可著手開發圖表、報表、海報生成等實務功能。

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