PHP图像处理:缩放、裁剪与优化
图像处理是Web应用开发中的关键任务之一。无论是用户头像、新闻缩略图还是商品图库,您几乎总是需要调整大小(resize)和裁剪(crop)图片。在PHP中,有两个主要的库:GD(内置)和Imagick(基于ImageMagick的扩展)。
在本文中,我们将介绍这两种方法,展示可运行的代码示例,并为您的项目提供选择建议。
1. GD库(GDLib)
GD是PHP的标准扩展,几乎在所有主机上都可用。它支持主要格式:JPEG、PNG、GIF、WEBP(PHP 7.1+)。缺点是重采样质量低于Imagick,但对于大多数任务来说,其功能已经足够。
1.1. 使用GD调整大小(resize)
imagecopyresampled()函数通过插值(平滑处理)创建新图像。以下是将图像按比例缩放至宽度300px的示例:
<?phpfunction resizeImageGD($srcFile, $destFile, $newWidth = 300) { // 获取原始图像尺寸 list($width, $height, $type) = getimagesize($srcFile); // 根据类型创建原始图像资源 switch ($type) { case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $src = imagecreatefrompng($srcFile); break; case IMAGETYPE_GIF: $src = imagecreatefromgif($srcFile); break; default: return false; } // 按比例计算新高度 $ratio = $width / $height; $newHeight = intval($newWidth / $ratio); // 创建所需尺寸的空白图像 $dst = imagecreatetruecolor($newWidth, $newHeight); // 为PNG/GIF启用Alpha通道 imagealphablending($dst, false); imagesavealpha($dst, true); // 重采样(复制并重新计算像素) imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); // 保存结果 imagejpeg($dst, $destFile, 85); // 质量85% // 释放内存 imagedestroy($src); imagedestroy($dst); return true;}
// 使用示例:resizeImageGD('photo.jpg', 'photo_thumb.jpg', 300);?>1.2. 使用GD裁剪(crop)
使用imagecopy()或imagecopyresampled()函数指定区域进行裁剪。以下示例裁剪中心200x200正方形:
<?phpfunction cropCenterGD($srcFile, $destFile, $cropSize = 200) { list($width, $height, $type) = getimagesize($srcFile); // 确定类型 $src = imagecreatefromjpeg($srcFile); // 以JPEG为例 // 计算中心正方形坐标 $x = ($width - $cropSize) / 2; $y = ($height - $cropSize) / 2; // 如果原始图像小于裁剪尺寸,则不裁剪 if ($width < $cropSize || $height < $cropSize) { $cropSize = min($width, $height); $x = 0; $y = 0; } $dst = imagecreatetruecolor($cropSize, $cropSize); imagecopy($dst, $src, 0, 0, $x, $y, $cropSize, $cropSize); imagejpeg($dst, $destFile, 90); imagedestroy($src); imagedestroy($dst);}
cropCenterGD('photo.jpg', 'cropped.jpg', 200);?>2. Imagick库
Imagick是一个强大的扩展,为ImageMagick提供面向对象的接口。支持超过200种格式,重采样质量优秀,可处理颜色、滤镜和动画。需要在服务器上安装(廉价主机上不一定可用)。