引言
一、PHP图片处理基础
1.1 GD库简介
1.2 创建图像资源
使用GD库,可以通过以下函数创建图像资源:
$image = imagecreatetruecolor($width, $height);
这个函数创建了一个指定宽度和高度的空白图像。
1.3 添加颜色
在图像上添加颜色需要使用imagecolorallocate函数:
$color = imagecolorallocate($image, 255, 255, 255); // 白色
这个函数返回一个颜色索引,可以用来填充图像或绘制图形。
二、图像处理技巧
2.1 图片生成
imagefill($image, 0, 0, $color); // 填充整个图像
imagerectangle($image, 10, 10, 100, 100, $color); // 绘制矩形
2.2 图片裁剪
$cropped = imagecrop($image, ['x' => 10, 'y' => 10, 'width' => 50, 'height' => 50]);
这个函数返回裁剪后的图像资源。
2.3 图片压缩
imagejpeg($image, 'output.jpg', 75); //JPEG格式,质量75
2.4 图片信息获取
list($width, $height, $type, $attr) = getimagesize('image.jpg');
这个函数返回图像的尺寸、类型和其他信息。
三、实战案例
3.1 图片上传
if ($_FILES['image']['error'] == 0) {
$image = $_FILES['image']['tmp_name'];
$imageType = exif_imagetype($image);
$image = imagecreatefromjpeg($image);
imagejpeg($image, 'uploads/' . $_FILES['image']['name']);
echo 'Image uploaded successfully!';
}
3.2 图片缩略图生成
function createThumbnail($imagePath, $thumbnailPath, $thumbnailWidth) {
$imageInfo = getimagesize($imagePath);
$image = imagecreatefromjpeg($imagePath);
$width = $imageInfo[0];
$height = $imageInfo[1];
$ratio = $thumbnailWidth / $width;
$newHeight = $height * $ratio;
$newImage = imagecreatetruecolor($thumbnailWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $thumbnailWidth, $newHeight, $width, $height);
imagejpeg($newImage, $thumbnailPath);
}