Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Resolutions to Aspect Ratios with PHP

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);
        }
    }
},
like image 955
Kirk Ouimet Avatar asked Feb 23 '23 09:02

Kirk Ouimet


2 Answers

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.

like image 149
Peter O. Avatar answered Feb 24 '23 23:02

Peter O.


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.

like image 38
Brian Fisher Avatar answered Feb 24 '23 22:02

Brian Fisher