PHP 入门教程
PHP GD 图像处理
本教程共 65 篇 · 第 36 篇 · 更新于 2026-07-24 · 约 5 分钟阅读
PHPPHP8GD库图像处理验证码水印缩略图
36. PHP GD 图像处理
本节目标:学会用 GD 库生成验证码、缩放图片、添加水印和转换格式。
GD 库是 PHP 内置的图像处理扩展。无需安装额外软件,就能完成常见的图片操作。
36.1 检查 GD 扩展
<?php
if (extension_loaded("gd")) {
echo "GD 扩展已启用";
echo "<br>版本信息:" . gd_info()["GD Version"];
} else {
echo "GD 扩展未启用,请在 php.ini 中取消注释 extension=gd";
}
36.2 生成验证码图片
验证码是最常见的 GD 应用场景:
<?php
session_start();
// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 分配颜色
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
$lineColor = imagecolorallocate($image, 200, 200, 200);
// 填充背景
imagefill($image, 0, 0, $bgColor);
// 生成随机验证码
$code = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 4);
$_SESSION["captcha"] = $code;
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
imageline(
$image,
rand(0, $width), rand(0, $height),
rand(0, $width), rand(0, $height),
$lineColor
);
}
// 写入文字
imagestring($image, 5, 30, 12, $code, $textColor);
// 输出图片
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
<!-- 在表单中使用 -->
<img src="captcha.php" alt="验证码">
<input type="text" name="captcha" placeholder="输入验证码">
Tip用
imagettftext()配合 TrueType 字体可以生成更美观、更难被 OCR 识别的验证码。
36.3 图片缩放
等比例缩放图片,生成缩略图:
<?php
function resizeImage(string $src, string $dst, int $maxWidth, int $maxHeight): bool {
// 获取原图信息
$info = getimagesize($src);
if ($info === false) {
return false;
}
[$origWidth, $origHeight, $type] = $info;
// 计算缩放后尺寸(保持比例)
$ratio = min($maxWidth / $origWidth, $maxHeight / $origHeight, 1);
$newWidth = (int) ($origWidth * $ratio);
$newHeight = (int) ($origHeight * $ratio);
// 创建画布
$srcImg = imagecreatefromstring(file_get_contents($src));
$dstImg = imagecreatetruecolor($newWidth, $newHeight);
// 缩放
imagecopyresampled(
$dstImg, $srcImg,
0, 0, 0, 0,
$newWidth, $newHeight,
$origWidth, $origHeight
);
// 保存
imagejpeg($dstImg, $dst, 90); // 90% 质量
imagedestroy($srcImg);
imagedestroy($dstImg);
return true;
}
// 使用
resizeImage("photo.jpg", "thumb.jpg", 200, 200);
Note
imagecopyresampled()比imagecopyresized()质量更好,推荐使用。
36.4 添加文字水印
<?php
function addWatermark(string $src, string $text, string $dst): void {
$image = imagecreatefromjpeg($src);
$width = imagesx($image);
$height = imagesy($image);
// 水印颜色(白色半透明)
$color = imagecolorallocatealpha($image, 255, 255, 255, 60);
// 字体路径(Linux 常用,Windows 需调整)
$font = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf";
// 计算文字位置(右下角)
$fontSize = 14;
$bbox = imagettfbbox($fontSize, 0, $font, $text);
$textWidth = $bbox[2] - $bbox[0];
$x = $width - $textWidth - 10;
$y = $height - 10;
imagettftext($image, $fontSize, 0, $x, $y, $color, $font, $text);
imagejpeg($image, $dst, 95);
imagedestroy($image);
}
addWatermark("photo.jpg", "© 2026 MySite", "watermarked.jpg");
TipWindows 环境下,字体路径类似
C:\Windows\Fonts\arial.ttf。没有 TTF 字体时,可用imagestring()代替,但效果较简陋。
36.5 图片格式转换
<?php
function convertImage(string $src, string $dst): bool {
$data = file_get_contents($src);
$image = imagecreatefromstring($data);
if ($image === false) {
return false;
}
$ext = strtolower(pathinfo($dst, PATHINFO_EXTENSION));
match ($ext) {
"jpg", "jpeg" => imagejpeg($image, $dst, 95),
"png" => imagepng($image, $dst),
"gif" => imagegif($image, $dst),
"webp" => imagewebp($image, $dst, 95),
default => imagejpeg($image, $dst, 95),
};
imagedestroy($image);
return true;
}
// PHP 8.0+ match 表达式让多分支更清晰
convertImage("input.png", "output.webp");
Note
imagewebp()需要 GD 编译时支持 WebP。WebP 格式体积更小,是现代网站的首选图片格式。
36.6 图片裁剪
<?php
function cropImage(
string $src,
string $dst,
int $x, int $y,
int $width, int $height
): void {
$srcImg = imagecreatefromstring(file_get_contents($src));
$dstImg = imagecreatetruecolor($width, $height);
imagecopy(
$dstImg, $srcImg,
0, 0,
$x, $y,
$width, $height
);
imagejpeg($dstImg, $dst, 95);
imagedestroy($srcImg);
imagedestroy($dstImg);
}
// 从 (100, 50) 开始裁剪 300x200 区域
cropImage("photo.jpg", "cropped.jpg", 100, 50, 300, 200);
来源:参考了 runoob「PHP 图像处理」、w3cschool「PHP 图像处理」等,改写后所得。