使用Wide Image PHP库调整图像大小时保持纵横比

时间:2013-10-19 18:31:59

标签: php image wideimage

我希望将图像调整为预定义的最大尺寸,并在WideImage Library的帮助下保持纵横比。

示例:

允许的最大尺寸:200x200

输入图像尺寸:300x200徽标(1.5:1纵横比),

电流输出图像尺寸:200x200

预期输出图像尺寸:200x133(1.5:1纵横比)。

目前,随着宽高比的改变,图像会失真。应该怎么做才能保持宽高比?

我正在使用下面的代码。

$targetWidth = 200;
$targetHeight = 200;

$sourceRatio = $sourceWidth / $sourceHeight;
$targetRatio = $targetWidth / $targetHeight;

if ( $sourceRatio < $targetRatio ) {
    $scale = $sourceWidth / $targetWidth;
} else {
    $scale = $sourceHeight / $targetHeight;
}

$resizeWidth = (int)($sourceWidth / $scale);
$resizeHeight = (int)($sourceHeight / $scale);


$img->resize($resizeWidth, $resizeHeight)

PS:我从Resize image without distortion keeping aspect ratio then crop excess using WideImage

得到了上述逻辑

1 个答案:

答案 0 :(得分:1)

这个简单的逻辑来帮助我。

$targetWidth = 200;
$targetHeight = 200;

$ratio = $srcWidth / $srcHeight;

if ($ratio > 1) {
    $resizeWidth = $targetWidth;
    $resizeHeight= $targetHeight / $ratio;
} else {
    $resizeWidth = $targetWidth * $ratio;
    $resizeHeight= $targetHeight;
}

$img->resize($resizeWidth, $resizeHeight)