一、PHP图片处理入门

1.1 创建和打开图像

在PHP中,可以通过GD库或Imagick扩展来创建或打开图像。

GD库

// 创建空白图像
$image = imagecreate(100, 100);

// 打开JPEG图像
$image = imagecreatefromjpeg('path/to/image.jpg');

// 打开PNG图像
$image = imagecreatefrompng('path/to/image.png');

// 打开GIF图像
$image = imagecreatefromgif('path/to/image.gif');

Imagick扩展

// 创建空白图像
$image = new Imagick();

// 打开JPEG图像
$image = new Imagick('path/to/image.jpg');

// 打开PNG图像
$image = new Imagick('path/to/image.png');

// 打开GIF图像
$image = new Imagick('path/to/image.gif');

1.2 获取图片的属性

// 获取图像宽度和高度
$width = imagesx($image);
$height = imagesy($image);

// 获取图像信息
$imageInfo = getimagesize('path/to/image.jpg');
$width = $imageInfo[0];
$height = $imageInfo[1];

二、调整图像大小

2.1 GD库

// 创建新图像
$newImage = imagecreatetruecolor($newWidth, $newHeight);

// 调整大小
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// 释放原图资源
imagedestroy($image);

// 设置新图像为当前图像
$image = $newImage;

2.2 Imagick扩展

// 调整大小
$image->resizeImage($newWidth, $newHeight, Imagick::FILTER_LANCZOS, 1);

三、裁剪图像

3.1 GD库

// 创建新图像
$newImage = imagecreatetruecolor($newWidth, $newHeight);

// 裁剪图像
imagecopyresampled($newImage, $image, 0, 0, $x, $y, $newWidth, $newHeight, $width - $x, $height - $y);

// 释放原图资源
imagedestroy($image);

// 设置新图像为当前图像
$image = $newImage;

3.2 Imagick扩展

// 裁剪图像
$image->cropImage($newWidth, $newHeight, $x, $y);

四、旋转图像

4.1 GD库

// 旋转图像
$angle = 90; // 旋转角度
$image = imagerotate($image, $angle, 0);

4.2 Imagick扩展

// 旋转图像
$image->rotateImage(Imagick::COLOR_RED, $angle);

五、添加水印

5.1 GD库

// 创建水印文字
$text = 'Watermark';

// 获取文字大小
$textWidth = imagettfbbox(5, 0, 'path/to/font.ttf', $text);

// 设置文字位置
$x = ($width - $textWidth[2]) / 2;
$y = ($height - $textWidth[7]) / 2;

// 绘制文字
imagettftext($image, 5, 0, $x, $y, 0xFFFFFF, 'path/to/font.ttf', $text);

// 释放原图资源
imagedestroy($image);

// 设置新图像为当前图像
$image = $newImage;

5.2 Imagick扩展

// 创建水印文字
$text = 'Watermark';

// 获取文字大小
$textWidth = $image->queryFontMetrics('Arial', $text);

// 设置文字位置
$x = ($width - $textWidth) / 2;
$y = ($height - 20) / 2;

// 绘制文字
$image->annotateImage('Arial', $x, $y, 0, $text);

// 释放原图资源
imagedestroy($image);

// 设置新图像为当前图像
$image = $newImage;

六、调整图像亮度和对比度

###