深入詳解PHP中圖像處理的利器GD庫(kù)的操作流程
在 PHP 開(kāi)發(fā)中,GD 庫(kù)是處理圖像的核心利器:生成驗(yàn)證碼、制作縮略圖、添加水印、繪制簡(jiǎn)單圖表…… 這些高頻需求都能通過(guò) GD 庫(kù)輕松實(shí)現(xiàn)。
開(kāi)啟需修改 php.ini,取消 extension=gd(Windows)或 extension=gd.so(Linux)前的注釋,重啟 Web 服務(wù)即可。
GD 庫(kù)基本操作流程
所有 GD 操作都遵循 “創(chuàng)建畫(huà)布 → 分配顏色 → 繪制內(nèi)容 → 輸出 / 保存 → 銷毀資源” 的流程:
<?php
// 1. 創(chuàng)建畫(huà)布(寬 400,高 200)
$image = imagecreatetruecolor(400, 200);
// 2. 分配顏色(RGB 值)
$white = imagecolorallocate($image, 255, 255, 255); // 白色
$black = imagecolorallocate($image, 0, 0, 0); // 黑色
// 3. 填充背景色
imagefill($image, 0, 0, $white);
// 4. 繪制內(nèi)容(比如寫(xiě)一行字)
imagestring($image, 5, 100, 90, 'Hello GD!', $black);
// 5. 輸出圖像(或保存到文件)
header('Content-Type: image/png'); // 告訴瀏覽器輸出的是 PNG 圖片
imagepng($image);
// 6. 銷毀資源,釋放內(nèi)存
imagedestroy($image);
?>
常用功能
繪制基本圖形
GD 庫(kù)支持繪制直線、矩形、圓形、橢圓等基礎(chǔ)圖形,適合制作簡(jiǎn)單圖表或標(biāo)記。
| 函數(shù) | 說(shuō)明 |
|---|---|
imageline() | 繪制直線 |
imagerectangle() | 繪制矩形(邊框) |
imagefilledrectangle() | 繪制填充矩形 |
imageellipse() | 繪制橢圓(圓形是橢圓的特例) |
imagefilledellipse() | 繪制填充橢圓 |
// 創(chuàng)建畫(huà)布
$image = imagecreatetruecolor(400, 300);
$white = imagecolorallocate($image, 255, 255, 255);
$red = imagecolorallocate($image, 255, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);
$green = imagecolorallocate($image, 0, 255, 0);
// 填充白色背景
imagefill($image, 0, 0, $white);
// 1. 繪制紅色直線(從 x1,y1 到 x2,y2)
imageline($image, 50, 50, 350, 50, $red);
// 2. 繪制藍(lán)色矩形邊框(x1,y1 左上角,x2,y2 右下角)
imagerectangle($image, 50, 80, 150, 180, $blue);
// 3. 繪制綠色填充矩形
imagefilledrectangle($image, 200, 80, 350, 180, $green);
// 4. 繪制紅色填充圓形(圓心 x,y,寬高相同即為圓)
imagefilledellipse($image, 200, 240, 80, 80, $red);
// 輸出圖像
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
生成縮略圖
網(wǎng)站上傳圖片時(shí),生成縮略圖是剛需。GD 庫(kù)通過(guò) imagecopyresampled() 實(shí)現(xiàn)高質(zhì)量縮放。
imagecreatefromjpeg()/imagecreatefrompng():從現(xiàn)有圖片創(chuàng)建畫(huà)布資源。imagecopyresampled():重采樣復(fù)制圖像(比imagecopyresized()更清晰,推薦使用)。
/**
* 生成等比例縮略圖
* @param string $srcPath 原圖路徑
* @param string $destPath 縮略圖保存路徑
* @param int $maxWidth 最大寬度
* @param int $maxHeight 最大高度
*/
function createThumbnail($srcPath, $destPath, $maxWidth = 200, $maxHeight = 200) {
// 獲取原圖信息
list($srcWidth, $srcHeight, $type) = getimagesize($srcPath);
// 根據(jù)圖片類型創(chuàng)建畫(huà)布
switch ($type) {
case IMAGETYPE_JPEG:
$srcImage = imagecreatefromjpeg($srcPath);
break;
case IMAGETYPE_PNG:
$srcImage = imagecreatefrompng($srcPath);
break;
default:
return false;
}
// 計(jì)算等比例縮放后的尺寸
$scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight);
$destWidth = $srcWidth * $scale;
$destHeight = $srcHeight * $scale;
// 創(chuàng)建縮略圖畫(huà)布
$destImage = imagecreatetruecolor($destWidth, $destHeight);
// 處理 PNG 透明背景(可選,若不需要可省略)
if ($type == IMAGETYPE_PNG) {
$transparent = imagecolorallocatealpha($destImage, 255, 255, 255, 127);
imagefill($destImage, 0, 0, $transparent);
imagesavealpha($destImage, true);
}
// 重采樣復(fù)制(核心步驟)
imagecopyresampled(
$destImage, $srcImage, // 目標(biāo)畫(huà)布、源畫(huà)布
0, 0, 0, 0, // 目標(biāo) x,y、源 x,y
$destWidth, $destHeight,// 目標(biāo)寬高
$srcWidth, $srcHeight // 源寬高
);
// 保存縮略圖
switch ($type) {
case IMAGETYPE_JPEG:
imagejpeg($destImage, $destPath, 90); // 90 是 JPEG 質(zhì)量
break;
case IMAGETYPE_PNG:
imagepng($destImage, $destPath);
break;
}
// 銷毀資源
imagedestroy($srcImage);
imagedestroy($destImage);
return true;
}
添加水印
文字水印
/**
* 添加文字水印
* @param string $srcPath 原圖路徑
* @param string $text 水印文字
* @param string $fontPath 字體文件路徑(需支持中文,比如 simhei.ttf)
*/
function addTextWatermark($srcPath, $text, $fontPath = './simhei.ttf') {
// 獲取原圖信息
list($width, $height, $type) = getimagesize($srcPath);
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcPath);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($srcPath);
break;
default:
return false;
}
// 分配水印顏色(半透明白色)
$watermarkColor = imagecolorallocatealpha($image, 255, 255, 255, 50); // 50 是透明度(0-127,越大越透明)
// 設(shè)置字體大小
$fontSize = 20;
// 計(jì)算文字位置(右下角)
$bbox = imagettfbbox($fontSize, 0, $fontPath, $text);
$textWidth = $bbox[2] - $bbox[0];
$textHeight = $bbox[1] - $bbox[7];
$x = $width - $textWidth - 20; // 距離右邊 20px
$y = $height - $textHeight - 20; // 距離下邊 20px
// 寫(xiě)入文字(使用 TrueType 字體,支持中文)
imagettftext($image, $fontSize, 0, $x, $y, $watermarkColor, $fontPath, $text);
// 保存圖片
$destPath = './watermark_text.jpg';
switch ($type) {
case IMAGETYPE_JPEG:
imagejpeg($image, $destPath, 90);
break;
case IMAGETYPE_PNG:
imagepng($image, $destPath);
break;
}
imagedestroy($image);
return $destPath;
}
圖片水印
/**
* 添加圖片水印
* @param string $srcPath 原圖路徑
* @param string $watermarkPath 水印圖片路徑(建議 PNG 透明圖)
*/
function addImageWatermark($srcPath, $watermarkPath) {
// 獲取原圖和水印圖信息
list($srcWidth, $srcHeight, $srcType) = getimagesize($srcPath);
list($wmWidth, $wmHeight, $wmType) = getimagesize($watermarkPath);
// 創(chuàng)建畫(huà)布
switch ($srcType) {
case IMAGETYPE_JPEG:
$srcImage = imagecreatefromjpeg($srcPath);
break;
case IMAGETYPE_PNG:
$srcImage = imagecreatefrompng($srcPath);
break;
default:
return false;
}
$wmImage = imagecreatefrompng($watermarkPath); // 假設(shè)水印是 PNG
// 計(jì)算水印位置(右下角)
$x = $srcWidth - $wmWidth - 20;
$y = $srcHeight - $wmHeight - 20;
// 合并水?。ūA?PNG 透明度)
imagecopy($srcImage, $wmImage, $x, $y, 0, 0, $wmWidth, $wmHeight);
// 保存圖片
$destPath = './watermark_image.jpg';
switch ($srcType) {
case IMAGETYPE_JPEG:
imagejpeg($srcImage, $destPath, 90);
break;
case IMAGETYPE_PNG:
imagepng($srcImage, $destPath);
break;
}
imagedestroy($srcImage);
imagedestroy($wmImage);
return $destPath;
}
生成驗(yàn)證碼
驗(yàn)證碼是防止惡意注冊(cè)、刷接口的常用手段,GD 庫(kù)生成驗(yàn)證碼的核心是 “隨機(jī)字符 + 干擾線 + 噪點(diǎn)”。
<?php
session_start(); // 開(kāi)啟 Session,用于保存驗(yàn)證碼
// 1. 創(chuàng)建畫(huà)布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 2. 分配顏色
$white = imagecolorallocate($image, 255, 255, 255);
$gray = imagecolorallocate($image, 200, 200, 200);
$darkGray = imagecolorallocate($image, 100, 100, 100);
// 3. 填充背景
imagefill($image, 0, 0, $white);
// 4. 繪制干擾線(3 條)
for ($i = 0; $i < 3; $i++) {
$lineColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 5. 繪制噪點(diǎn)(50 個(gè))
for ($i = 0; $i < 50; $i++) {
$dotColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150));
imagesetpixel($image, rand(0, $width), rand(0, $height), $dotColor);
}
// 6. 生成隨機(jī)驗(yàn)證碼
$chars = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; // 去掉易混淆的 0、1、O、l
$code = '';
for ($i = 0; $i < 4; $i++) {
$code .= $chars[rand(0, strlen($chars) - 1)];
}
// 保存到 Session,用于后續(xù)驗(yàn)證
$_SESSION['captcha'] = strtolower($code);
// 7. 寫(xiě)入驗(yàn)證碼文字
$fontSize = 16;
$fontPath = './simhei.ttf'; // 可選,若沒(méi)有可用 imagestring
for ($i = 0; $i < 4; $i++) {
$charColor = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
$x = 15 + $i * 25;
$y = rand(25, 35);
imagettftext($image, $fontSize, rand(-10, 10), $x, $y, $charColor, $fontPath, $code[$i]);
}
// 8. 輸出圖像
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
注意事項(xiàng)
- 記得銷毀資源:每次 GD 操作后,務(wù)必用
imagedestroy()銷毀圖像資源,避免內(nèi)存泄漏。 - 輸出前無(wú)任何輸出:在
header('Content-Type: image/png')前,不能有任何 HTML 標(biāo)簽、空格或換行,否則會(huì)導(dǎo)致圖像無(wú)法顯示。 - 處理大圖片注意內(nèi)存:處理高分辨率圖片時(shí),可能會(huì)超出 PHP 內(nèi)存限制,可在代碼開(kāi)頭臨時(shí)調(diào)整:
ini_set('memory_limit', '256M');。 - 中文支持用 TrueType 字體:
imagestring()不支持中文,需用imagettftext()配合.ttf字體文件(如simhei.ttf黑體)。 - 優(yōu)先使用
imagecopyresampled():縮放圖片時(shí),imagecopyresampled()會(huì)進(jìn)行重采樣,生成的縮略圖更清晰,不要用imagecopyresized()。
以上就是深入詳解PHP中圖像處理的利器GD庫(kù)的操作流程的詳細(xì)內(nèi)容,更多關(guān)于PHP圖像處理GD庫(kù)使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PHP+MySQL實(shí)現(xiàn)模糊查詢員工信息功能示例
這篇文章主要介紹了PHP+MySQL實(shí)現(xiàn)模糊查詢員工信息功能,結(jié)合實(shí)例形式分析了php連接mysql數(shù)據(jù)庫(kù)及使用like語(yǔ)句進(jìn)行模糊查詢與顯示相關(guān)操作技巧,需要的朋友可以參考下2018-06-06
PHP 遠(yuǎn)程關(guān)機(jī)實(shí)現(xiàn)代碼
大家都知道PHP是用于開(kāi)發(fā)網(wǎng)站的腳本語(yǔ)言,但在網(wǎng)上學(xué)習(xí)時(shí)發(fā)現(xiàn)了下面的這一段php腳本代碼,它可以實(shí)現(xiàn)遠(yuǎn)程關(guān)閉計(jì)算機(jī),懂PHP的朋友來(lái)研究一下吧。2009-11-11
PHP文字轉(zhuǎn)圖片功能原理與實(shí)現(xiàn)方法分析
這篇文章主要介紹了PHP文字轉(zhuǎn)圖片功能原理與實(shí)現(xiàn)方法,結(jié)合具體實(shí)例形式分析了php基于gd2擴(kuò)展庫(kù)生成圖片的相關(guān)配置及使用方法,需要的朋友可以參考下2017-08-08

