引言

准备工作

在开始之前,请确保您的PHP环境中已经安装了GD库。GD库是PHP处理图像的基础,可以通过编辑php.ini文件来启用。

extension=gd

重启服务器后,GD库即可生效。

创建图片文件

1. 使用imagecreatetruecolor()

$width = 100;
$height = 100;
$image = imagecreatetruecolor($width, $height);

2. 使用imagecreatefromjpeg()

$image = imagecreatefromjpeg('path/to/image.jpg');

3. 使用imagecreatefrompng()

$image = imagecreatefrompng('path/to/image.png');

4. 使用imagecreatefromgif()

$image = imagecreatefromgif('path/to/image.gif');

图片处理技巧

1. 调整图片大小

$dst_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dst_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

2. 裁剪图片

$dst_image = imagecreatetruecolor($new_width, $new_height);
imagecopy($dst_image, $image, 0, 0, $x, $y, $new_width, $new_height);

3. 旋转图片

$dst_image = imagerotate($image, -90, 0);

4. 添加水印

$font_size = 5;
$font_color = imagecolorallocate($image, 255, 255, 255);
imagestring($image, $font_size, 10, 10, 'Watermark', $font_color);

输出图片

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

总结