这是我个人的图像调整大小代码袋中的代码。首先,您需要的数据:
list($originalWidth, $originalHeight) = getimagesize($imageFile);
$ratio = $originalWidth / $originalHeight;
然后,该算法尽可能地将图像适合目标尺寸,保持原始长宽比,而不将图像拉伸得比原始尺寸更大:
$targetWidth = $targetHeight = min($size, max($originalWidth, $originalHeight));
if ($ratio < 1) {
$targetWidth = $targetHeight * $ratio;
} else {
$targetHeight = $targetWidth / $ratio;
}
$srcWidth = $originalWidth;
$srcHeight = $originalHeight;
$srcX = $srcY = 0;
这会裁剪图像以完全填充目标尺寸,而不是拉伸它:
$targetWidth = $targetHeight = min($originalWidth, $originalHeight, $size);
if ($ratio < 1) {
$srcX = 0;
$srcY = ($originalHeight / 2) - ($originalWidth / 2);
$srcWidth = $srcHeight = $originalWidth;
} else {
$srcY = 0;
$srcX = ($originalWidth / 2) - ($originalHeight / 2);
$srcWidth = $srcHeight = $originalHeight;
}
这实际上是调整大小:
$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetImage, $originalImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
在这种情况下$size
宽度和高度只是一个数字(方形目标尺寸)。我确信您可以修改它以使用非方形目标。它还应该为您提供有关可以使用哪些其他调整大小算法的灵感。