PHP修改图片大小

<?php
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight) {
list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceImage);
switch ($sourceType) {
case IMAGETYPE_JPEG:
$sourceResource = imagecreatefromjpeg($sourceImage);
break;
case IMAGETYPE_PNG:
$sourceResource = imagecreatefrompng($sourceImage);
break;
case IMAGETYPE_GIF:
$sourceResource = imagecreatefromgif($sourceImage);
break;
default:
return false;
}
$targetWidth = $sourceWidth;
$targetHeight = $sourceHeight;
if ($sourceWidth > $maxWidth || $sourceHeight > $maxHeight) {
$aspectRatio = $sourceWidth / $sourceHeight;
if (($maxWidth / $maxHeight) > $aspectRatio) {
$targetWidth = $maxHeight * $aspectRatio;
$targetHeight = $maxHeight;
} else {
$targetWidth = $maxWidth;
$targetHeight = $maxWidth / $aspectRatio;
}
}
$targetResource = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetResource, $sourceResource, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
switch ($sourceType) {
case IMAGETYPE_JPEG:
imagejpeg($targetResource, $targetImage, 80); // 80 是图片质量,可根据需求调整
break;
case IMAGETYPE_PNG:
imagepng($targetResource, $targetImage);
break;
case IMAGETYPE_GIF:
imagegif($targetResource, $targetImage);
break;
default:
return false;
}
imagedestroy($sourceResource);
imagedestroy($targetResource);
return true;
}

//这个命令尝试修改图片大小,注意要启用GD库。
resizeImage(’11.png’, ’22.png’, 1000, 600);