PHP图像处理:GD与Imagick库
图像处理是Web开发中的关键任务之一。在PHP中,主要使用两个库:GD(内置)和Imagick(ImageMagick的封装)。本文将介绍它们的功能,学习如何调整大小、裁剪、添加水印以及优化图像。
1. GD库
GD是PHP的标准扩展,大多数主机都支持。它可以创建、修改和保存JPEG、PNG、GIF、WebP格式的图像。
加载与检查:
<?php// 检查GD扩展是否已安装if (extension_loaded('gd') && function_exists('gd_info')) { echo "GD已安装:"; print_r(gd_info());} else { echo "未找到GD";}?>1.1 调整图像大小(resize)
最常见的场景是将图像缩小到所需尺寸并保持比例。
<?phpfunction resizeImage($sourcePath, $destPath, $newWidth, $newHeight) { // 获取原始图像尺寸 list($width, $height, $type) = getimagesize($sourcePath); // 从源文件创建资源 switch ($type) { case IMAGETYPE_JPEG: $source = imagecreatefromjpeg($sourcePath); break; case IMAGETYPE_PNG: $source = imagecreatefrompng($sourcePath); break; case IMAGETYPE_GIF: $source = imagecreatefromgif($sourcePath); break; default: return false; } // 创建新图像 $newImage = imagecreatetruecolor($newWidth, $newHeight); // 保留PNG/GIF的透明度 imagealphablending($newImage, false); imagesavealpha($newImage, true); // 复制并缩放 imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); // 保存结果 imagejpeg($newImage, $destPath, 85); // 质量85% // 释放内存 imagedestroy($source); imagedestroy($newImage); return true;}
// 使用示例resizeImage('photo.jpg', 'photo_thumb.jpg', 300, 200);?>1.2 裁剪图像(crop)
裁剪可以从图像中心提取所需尺寸的部分。
<?phpfunction cropCenter($sourcePath, $destPath, $cropWidth, $cropHeight) { list($width, $height) = getimagesize($sourcePath); $source = imagecreatefromjpeg($sourcePath); // 计算中心坐标 $x = ($width - $cropWidth) / 2; $y = ($height - $cropHeight) / 2; $newImage = imagecreatetruecolor($cropWidth, $cropHeight); imagecopyresampled($newImage, $source, 0, 0, $x, $y, $cropWidth, $cropHeight, $cropWidth, $cropHeight); imagejpeg($newImage, $destPath, 90); imagedestroy($source); imagedestroy($newImage);}
cropCenter('photo.jpg', 'photo_cropped.jpg', 400, 400);?>1.3 添加水印
在图像上添加文字或Logo。
<?phpfunction addWatermarkText($sourcePath, $destPath, $text = "© PythonLib.ru") { $source = imagecreatefromjpeg($sourcePath); $width = imagesx($source); $height = imagesy($source); // 文字颜色(白色半透明) $color = imagecolorallocatealpha($source, 255, 255, 255, 50); // 字体大小(使用内置字体) $fontSize = 5; $x = 10; $y = $height - 20; imagestring($source, $fontSize, $x, $y, $text, $color); imagejpeg($source, $destPath, 90); imagedestroy($source);}
addWatermarkText('photo.jpg', 'photo_watermarked.jpg');?>