从图片的宽度和高度获取纵横比(PHP或JS)

4

我简直不敢相信找不到这个公式。我正在使用一个名为SLIR的PHP脚本来调整图像大小。脚本要求指定一个用于裁剪的宽高比。我希望根据表单中用户输入的图像宽度和高度,获取宽高比。例如,如果用户输入1024x768的图像,则应该得到4:3的宽高比。但是,我无论如何都找不到一个在PHP或Javascript中可用的公式示例,可以基于已知的宽度和高度来计算宽高比并将其插入变量中。


1
我不确定我理解得是否正确,但也许你正在寻找的是1024/768(宽度/高度)? - Fabrizio
6个回答

11
如果您能获取其中之一:高度、宽度,则可以计算缺失的宽度或高度:
原始宽度 * 新高度 / 原始高度 = 新宽度;
原始高度 * 新宽度 / 原始宽度 = 新高度;
或者如果您只想得到一个比例:
原始宽度 / 原始高度 = 比例。

7

要获得宽高比,只需像分数一样简化宽度和高度,例如:

1024      4
----  =  ---
768       3

PHP代码:

function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        gcd($b, $r) :
        abs($b);
}

  $gcd=gcd(1024,768);

  echo "Aspect ratio = ". (1024/$gcd) . ":" . (768/$gcd);

3
这里有一个更简单的整数最大公约数比率替代方案:
function ratio( $x, $y ){
    $gcd = gmp_strval(gmp_gcd($x, $y));
    return ($x/$gcd).':'.($y/$gcd);
}

请求echo ratio(25,5);的返回结果是5:1

如果你的服务器没有编译GMP函数……

function gcd( $a, $b ){
    return ($a % $b) ? gcd($b,$a % $b) : $b;
}
function ratio( $x, $y ){
    $gcd = gcd($x, $y);
    return ($x/$gcd).':'.($y/$gcd);
}

当图片尺寸为662x440时,为什么会得到331:220,而期望的是6:4 - Tim Bogdanov
1
此函数的目的在于将比率化简至最低公分母。例如,6:4 = 660x440 ... 而不是 662:440,其最低准确比率 = 331:220。这样说您明白了吗? - designosis

1

你不需要进行任何计算。

仅仅因为它说是长宽比,并不意味着它必须是一组有限的常用比例之一。它可以是由冒号分隔的任意一对数字。

引用自SLIR使用指南

For example, if you want your image to be exactly 150 pixels wide by 100 pixels high, you could do this:

<img src="/slir/w150-h100-c150:100/path/to/image.jpg" alt="Don't forget your alt text" /> 

Or, more concisely:

<img src="/slir/w150-h100-c15:10/path/to/image.jpg" alt="Don't forget your alt text" />
请注意,他们甚至没有把它进一步缩小到。.
因此,只需使用用户输入的值:1024: 768
如果您想要简洁明了,可以计算宽度和高度的最大公约数,并将它们都除以它。这将把您的1024: 768缩小到4:3

0
如果您没有安装GMP数学扩展,这里是我使用的无依赖解决方案:
function aspect_ratio($width, $height) {

  $ratio = [$width, $height];

  for ($x = $ratio[1]; $x > 1; $x--) {
    if (($ratio[0] % $x) == 0 && ($ratio[1] % $x) == 0) {
      $ratio = [$ratio[0] / $x, $ratio[1] / $x];
    }
  }

  return implode(':', $ratio);
}

它可以像这样使用:

echo aspect_ratio(1920, 1080); // Outputs 16:9
echo aspect_ratio(1024, 768); // Outputs 4:3
echo aspect_ratio(200, 300); // Outputs 2:3

来源:https://forums.digitalpoint.com/threads/how-i-will-get-ratio-of-2-number-in-php.937696/


0
这里有一个更简单的选择,可以在没有gmp扩展的情况下获取宽高比。
<?php

function getAspectRatio(int $width, int $height)
{
    // search for greatest common divisor
    $greatestCommonDivisor = static function($width, $height) use (&$greatestCommonDivisor) {
        return ($width % $height) ? $greatestCommonDivisor($height, $width % $height) : $height;
    };

    $divisor = $greatestCommonDivisor($width, $height);

    return $width / $divisor . ':' . $height / $divisor;
}

echo getAspectRatio(1280, 1024);
echo PHP_EOL;
echo getAspectRatio(1275, 715);

来源:https://gist.github.com/wazum/5710d9ef064caac7b909a9e69867f53b

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接