在PHP中,GD库是一个非常强大的图像处理库,可以用来创建和编辑图像。以下是一个使用GD库实现图片处理的实例,包括添加文字、改变图片大小、添加边框等效果。
1. 添加文字到图片
以下代码将演示如何将文字添加到图片上:

```php
// 创建图像资源
$image = imagecreatefromjpeg('example.jpg');
// 设置文字颜色
$color = imagecolorallocate($image, 255, 255, 255); // 白色
// 添加文字
imagestring($image, 5, 10, 10, 'Hello, World!', $color);
// 输出图像
header('Content-Type: image/jpeg');
imagejpeg($image);
>
```
| 函数 | 描述 |
|---|---|
| imagecreatefromjpeg | 从JPEG文件创建图像 |
| imagecolorallocate | 分配颜色 |
| imagestring | 在图像上输出字符串 |
2. 改变图片大小
以下代码将演示如何改变图片大小:
```php
// 创建图像资源
$image = imagecreatefromjpeg('example.jpg');
// 设置新的图片宽度和高度
$new_width = 300;
$new_height = 200;
// 创建新图像
$image_p = imagecreatetruecolor($new_width, $new_height);
// 复制并调整大小
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, imagesx($image), imagesy($image));
// 输出图像
header('Content-Type: image/jpeg');
imagejpeg($image_p);
>
```
| 函数 | 描述 |
|---|---|
| imagecreatetruecolor | 创建一个空白图像 |
| imagecopyresampled | 复制并调整大小的图像 |
3. 添加边框到图片
以下代码将演示如何为图片添加边框:
```php
// 创建图像资源
$image = imagecreatefromjpeg('example.jpg');
// 设置边框颜色和宽度
$border_color = imagecolorallocate($image, 0, 0, 0); // 黑色
$border_width = 5;
// 计算边框位置
$border_x = ($image_width - $border_width) / 2;
$border_y = ($image_height - $border_width) / 2;
// 添加边框
for ($i = 0; $i < $border_width; $i++) {
imageline($image, $border_x, $border_y + $i, $border_x + $image_width - $border_width, $border_y + $i, $border_color);
imageline($image, $border_x + $i, $border_y, $border_x + $i, $border_y + $image_height - $border_width, $border_color);
}
// 输出图像
header('Content-Type: image/jpeg');
imagejpeg($image);
>
```
| 函数 | 描述 |
|---|---|
| imageline | 在图像上画线 |
| imagecolorallocate | 分配颜色 |
通过以上实例,我们可以看到使用PHP和GD库进行图像处理的基本方法。这些方法可以帮助我们在网页上展示丰富的图像效果。









