使用PHP将分辨率转换为Aspect比率

时间:2011-11-15 05:49:07

标签: php string image image-processing

我需要一些可能非常基本的帮助。我正在研究一个接收这些可能的输入字符串的PHP函数(这些是示例,它可以是任何分辨率):

1600x900
1440x900
1366x768
1360x768
1280x1024
1280x800
1024x1024
1024x768
640x960
320x480
320x480
etc

我想处理这些字符串中的任何一个并返回适当的宽高比字符串,格式如下:

5:4
4:3
16:9
etc

有关解决此问题的简单方法的任何想法吗?

编辑:这是我一直在使用的参考图表:

http://en.wikipedia.org/wiki/File:Vector_Video_Standards2.svg

编辑:这是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);
        }
    }
},

4 个答案:

答案 0 :(得分:3)

我会这样接近:

$numbers = explode($input,'x');
$numerator = $numbers[0];
$denominator = $numbers[1];
$gcd = gcd($numerator, $denominator);
echo ($numerator / $gcd) . ":" . ($denominator / $gcd);

如果您没有安装GMP - GNU Multiple Precision扩展,则必须定义gcd功能。 comments of the documentation中有一些示例。

答案 1 :(得分:3)

以下功能可能会更好:

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));
  }
 }
}

我将此代码放在公共领域。

答案 2 :(得分:2)

找到分辨率宽度和高度的GCD。除以此GCD,您将获得两个宽高比数字。

编辑:Brian说它更好=]

答案 3 :(得分:1)

不幸的是,如果您指的是所有可能的屏幕,这不是一个简单的问题。例如,这是一个1024x1024的屏幕,它是16:9:http://www.hdtvsolutions.com/AKAI-PDP-4225M.htm

对于方形像素(大多数计算机显示器),其他人建议的GCD方法可行。