Reputation: 28374
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);
}
}
},
Upvotes: 4
Views: 1103
Reputation: 32898
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.
Upvotes: 3
Reputation: 39277
Unfortunately this isn't a simple problem if you are referring to all possible screens. For example, here's a 1024x1024 screen that's 16:9: http://www.hdtvsolutions.com/AKAI-PDP-4225M.htm
For square-pixels (most computer monitors) the GCD approach suggested by others will work.
Upvotes: 0
Reputation: 2841
Find the GCD of the width and height of the resolution. Divide by this GCD, and you get the two aspect ratio numbers.
Edit: Brian said it better =]
Upvotes: 2
Reputation: 23989
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.
Upvotes: 3