1. 准备工作

在开始之前,请确保你的服务器上安装了PHP和GD库。GD库是PHP处理图像的基础,它提供了多种图像处理功能。

2. 读取图片

// 读取JPEG图片
$image = imagecreatefromjpeg('example.jpg');

// 读取PNG图片
$image = imagecreatefrompng('example.png');

// 读取GIF图片
$image = imagecreatefromgif('example.gif');

3. 获取图片信息

// 获取图片宽度
$width = imagesx($image);

// 获取图片高度
$height = imagesy($image);

4. 图片修改技巧

4.1 图片缩放

// 创建新图像
$dest = imagecreatetruecolor($new_width, $new_height);

// 缩放图片
imagecopyresampled($dest, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// 输出新图像
imagejpeg($dest, 'resized_example.jpg');

4.2 图片裁剪

// 裁剪图片
$crop = imagecrop($image, ['x' => 50, 'y' => 50, 'width' => 100, 'height' => 100]);

// 输出裁剪后的图片
imagejpeg($crop, 'cropped_example.jpg');

4.3 图片旋转

// 旋转图片
$rotated = imagerotate($image, 90, 0);

// 输出旋转后的图片
imagejpeg($rotated, 'rotated_example.jpg');

4.4 图片水印

使用imagestring()imagepngtext()函数可以添加文字水印。

// 添加文字水印
imagestring($image, 2, 10, 10, 'Watermark', 2);

// 输出带有水印的图片
imagejpeg($image, 'watermarked_example.jpg');

4.5 图片格式转换

// 转换为PNG格式
imagepng($image, 'converted_example.png');

5. 输出图片

// 输出JPEG图片
header('Content-Type: image/jpeg');
imagejpeg($image);

// 释放内存
imagedestroy($image);

总结