在PHP中,图片缩放通常可以通过GD库或Imagick扩展来实现。这里我将提供一个使用GD库进行图片缩放的基础示例。
<?php
function resizeImage($sourceFile, $destFile, $desiredWidth, $desiredHeight) {
// 获取图片信息
list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceFile);
// 根据源图片的宽高比计算新的宽高
$sourceAspectRatio = $sourceWidth / $sourceHeight;
$desiredAspectRatio = $desiredWidth / $desiredHeight;
if ($sourceAspectRatio > $desiredAspectRatio) {
// 如果源图片的宽高比大于目标宽高比,则按宽度缩放
$resizedWidth = (int)$desiredWidth;
$resizedHeight = (int)($desiredWidth / $sourceAspectRatio);
} else {
// 否则,按高度缩放
$resizedHeight = (int)$desiredHeight;
$resizedWidth = (int)($desiredHeight * $sourceAspectRatio);
}
// 创建新的图片资源
switch ($sourceType) {
case IMAGETYPE_GIF:
$sourceGdImage = imagecreatefromgif($sourceFile);
break;
case IMAGETYPE_JPEG:
$sourceGdImage = imagecreatefromjpeg($sourceFile);
break;
case IMAGETYPE_PNG:
$sourceGdImage = imagecreatefrompng($sourceFile);
break;
default:
throw new Exception('Unsupported image type.');
}
$destGdImage = imagecreatetruecolor($desiredWidth, $desiredHeight);
// 将源图片复制到新图片资源中,并按比例缩放
imagecopyresampled($destGdImage, $sourceGdImage,
0, 0, 0, 0,
$desiredWidth, $desiredHeight,
$sourceWidth, $sourceHeight);
// 根据目标格式保存图片
switch (strtolower(pathinfo($destFile, PATHINFO_EXTENSION))) {
case 'gif':
imagegif($destGdImage, $destFile);
break;
case 'jpg':
case 'jpeg':
imagejpeg($destGdImage, $destFile);
break;
case 'png':
imagepng($destGdImage, $destFile);
break;
default:
throw new Exception('Unsupported image format.');
}
// 释放内存
imagedestroy($sourceGdImage);
imagedestroy($destGdImage);
}
// 使用示例
$sourceFile = 'path/to/your/source/image.jpg';
$destFile = 'path/to/your/destination/image_resized.jpg';
$desiredWidth = 800;
$desiredHeight = 600;
resizeImage($sourceFile, $destFile, $desiredWidth, $desiredHeight);
?>
这个函数`resizeImage`接受源图片文件路径、目标图片文件路径、目标宽度和高度作为参数,然后根据源图片的宽高比进行缩放,并将缩放后的图片保存到指定位置。注意,你需要确保PHP环境已经启用了GD库。