I need some help with something that is probably very basic. I'm working on a PHP function that receives these possible input strings (these are examples, it could be any resolution):
1600x900
1440x900
1366x768
1360x768
1280x1024
1280x800
1024x1024
1024x768
640x960
320x480
320x480
etc
I'd like to process any one of these strings and return the appropriate aspect ratio string, in this format:
5:4
4:3
16:9
etc
Any thoughts on a simple way to approach this problem?
Edit: Here's a reference chart I've been working with:
http://en.wikipedia.org/wiki/File:Vector_Video_Standards2.svg
Edit: Here's the answer in JavaScript:
aspectRatio: function(a, b) {
var total = a + b;
for(var i = 1; i <= 40; i++) {
var arx = i * 1.0 * a / total;
var brx = i * 1.0 * b / total;
if(i == 40 || (
Math.abs(arx - Math.round(arx)) <= 0.02 &&
Math.abs(brx - Math.round(brx)) <= 0.02)) {
// Accept aspect ratios within a given tolerance
return Math.round(arx)+':'+Math.round(brx);
}
}
},
The following function may work better:
function aspectratio($a,$b){
# sanity check
if($a<=0 || $b<=0){
return array(0,0);
}
$total=$a+$b;
for($i=1;$i<=40;$i++){
$arx=$i*1.0*$a/$total;
$brx=$i*1.0*$b/$total;
if($i==40||(
abs($arx-round($arx))<=0.02 &&
abs($brx-round($brx))<=0.02)){
# Accept aspect ratios within a given tolerance
return array(round($arx),round($brx));
}
}
}
I place this code in the public domain.
I would approach it this way:
$numbers = explode($input,'x');
$numerator = $numbers[0];
$denominator = $numbers[1];
$gcd = gcd($numerator, $denominator);
echo ($numerator / $gcd) . ":" . ($denominator / $gcd);
You have to define the gcd function if you don't have the GMP — GNU Multiple Precision extension installed. There are examples in the comments of the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With