實際上,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
* I了 「標準」 的寬高比的列表從wikipedia,如果你想要的參考。
爲什麼這不起作用? 你已經找到了根據你的代碼的長寬比(哪個工作)。哪裏有問題? –
寬高比爲3776,高爲2520的照片的寬高比爲3:2。不是472:315(縱橫比是否存在?!)。所以我的問題。 – Erik
實際上,3780x2520是3:2的寬高比;因爲你使用3776的寬度,472:315是正確的比例。如果你做分區,它會達到1.498,這相當接近。如果你想要「完美」的比例(比如標準的「3:2」或「16:9」),你可以將檢測到的比率傳遞給另一個函數來輪換它們以找到最近/最佳匹配。 – newfurniturey