显示正确的宽高比(Show correct aspect ratio)

2019-10-17 08:16发布

我试图让照片的高宽比,但下面的代码显示了高度与宽度3776和2520的照片错的纵横比(472:315),但它显示了在照片与3968的宽度和2232正确的纵横比在高度虽然(16:9)。

function gcd($a, $b) {
    if($a == 0 || $b == 0) {
        return abs(max(abs($a), abs($b)));
    }

    $r = $a % $b;
    return ($r != 0) ? gcd($b, $r) : abs($b);
}

$gcd = gcd($widtho, $heighto);
echo ($widtho / $gcd).':'.($heighto / $gcd);

我怎样才能解决我的问题?

提前致谢。

Answer 1:

实际上,3780x2520是3的纵横比:2; 因为你使用3776的宽度,472:315是正确的比例。 如果你这样做了分工,它出来到1.498,这是非常接近,足以1.5考虑四舍五入到3:2。

如果只希望的“标准”比例(如“3:2”​​或“16:9”),可以将检测到的比率传递到舍入他们找到最近/最佳匹配代替另一功能。

这是溅功能一起为你舍入,可以做(只针对你的榜样尺寸测试,所以我不能保证100次%的成功还):

function findBestMatch($ratio) {
    $commonRatios = array(
        array(1, '1:1'), array((4 / 3), '4:3'), array((3 / 2), '3:2'),
        array((5 / 3), '5:3'), array((16 / 9), '16:9'), array(3, '3')
    );

    list($numerator, $denominator) = explode(':', $ratio);
    $value = $numerator / $denominator;

    $end = (count($commonRatios) - 1);
    for ($i = 0; $i < $end; $i++) {
        if ($value == $commonRatios[$i][0]) {
            // we have an equal-ratio; no need to check anything else!
            return $commonRatios[$i][1];
        } else if ($value < $commonRatios[$i][0]) {
            // this can only happen if the ratio is `< 1`
            return $commonRatios[$i][1];
        } else if (($value > $commonRatios[$i][0]) && ($value < $commonRatios[$i + 1][0])) {
            // the ratio is in-between the current common-ratio and the next in the list
            // find whichever one it's closer-to and return that one.
            return (($value - $commonRatios[$i][0]) < ($commonRatios[$i + 1][0] - $value)) ? $commonRatios[$i][1] : $commonRatios[$i + 1][1];
        }
    }

    // we didn't find a match; that means we have a ratio higher than our biggest common one
    // return the original value
    return $ratio;
}

要使用此功能,您在比字符串(不是数值)将它传递,它会试图“找到一个最佳匹配”的比例共同名单。

实例:

$widtho = 3968;
$heighto = 2232;
$gcd = gcd($widtho, $heighto);
$ratio = ($widtho / $gcd).':'.($heighto / $gcd);
echo 'found: ' . $ratio . "\n";
echo 'match: ' . findBestMatch($ratio) . "\n";

$widtho = 3776;
$heighto = 2520;
$gcd = gcd($widtho, $heighto);
$ratio = ($widtho / $gcd).':'.($heighto / $gcd);
echo 'found: ' . $ratio . "\n";
echo 'match: ' . findBestMatch($ratio) . "\n";

$widtho = 3780;
$heighto = 2520;
$gcd = gcd($widtho, $heighto);
$ratio = ($widtho / $gcd).':'.($heighto / $gcd);
echo 'found: ' . $ratio . "\n";
echo 'match: ' . findBestMatch($ratio) . "\n";

上述试验将输出以下内容:

found: 16:9
match: 16:9

found: 472:315
match: 3:2

found: 3:2
match: 3:2

*我把“标准”宽高比的名单从维基百科 ,如果你想有一个参考。



文章来源: Show correct aspect ratio