准备工作
在开始之前,请确保您的PHP环境中已经安装了GD库,这是处理图像的基础。您可以通过以下命令检查GD库是否安装:
if (extension_loaded('gd')) {
echo "GD库已安装";
} else {
echo "GD库未安装,请安装GD库";
}
创建缩放函数
function imageResize($sourceImage, $destinationImage, $maxWidth, $maxHeight) {
// 获取源图片信息
$imageInfo = getimagesize($sourceImage);
$width = $imageInfo[0];
$height = $imageInfo[1];
// 计算缩放比例
$ratioWidth = $maxWidth / $width;
$ratioHeight = $maxHeight / $height;
$ratio = min($ratioWidth, $ratioHeight);
// 计算缩放后的尺寸
$newWidth = $width * $ratio;
$newHeight = $height * $ratio;
// 创建新图像资源
switch ($imageInfo[2]) {
case IMAGETYPE_JPEG:
$newImage = imagecreatefromjpeg($sourceImage);
break;
case IMAGETYPE_GIF:
$newImage = imagecreatefromgif($sourceImage);
break;
case IMAGETYPE_PNG:
$newImage = imagecreatefrompng($sourceImage);
break;
default:
return "不支持的图片格式";
}
// 缩放图像
$resizedImage = imagescale($newImage, $newWidth, $newHeight);
// 保存缩放后的图像
switch ($imageInfo[2]) {
case IMAGETYPE_JPEG:
imagejpeg($resizedImage, $destinationImage);
break;
case IMAGETYPE_GIF:
imagegif($resizedImage, $destinationImage);
break;
case IMAGETYPE_PNG:
imagepng($resizedImage, $destinationImage);
break;
}
// 释放资源
imagedestroy($newImage);
imagedestroy($resizedImage);
return "缩放成功";
}
使用缩放函数
$sourceImage = 'path/to/source/image.jpg';
$destinationImage = 'path/to/destination/image.jpg';
$maxWidth = 500;
$maxHeight = 500;
$result = imageResize($sourceImage, $destinationImage, $maxWidth, $maxHeight);
echo $result;