PHP 根据宽高比调整图像大小

PHP Image resizing with aspect ratio

我有这个 PHP 脚本可以将图像大小调整为 50%(或任何预设百分比)

$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);

现在,如果我想将 $new_width 指定为 1200(px)并告诉 $new_height 自动计算保持纵横比并将新图像的名称设置为 "test-2.jpg"

$filename = 'test.jpg';

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 1200;
$new_height = // MUST BE AUTO;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);

你是这个意思吗?

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 1200;
$new_height = ($height/$width)*$new_width;

"Keep aspect ratio" 表示以下等式必须成立:

$new_height / $new_width == $height / $width

因此,新高度的计算公式为:

$new_height = ceil($height * ($new_width/$width));

请注意,ceil 确保新高度为整数值且至少 1(假设新宽度和旧宽度+高度均为正值)。