我简直不敢相信找不到这个公式。我正在使用一个名为SLIR的PHP脚本来调整图像大小。脚本要求指定一个用于裁剪的宽高比。我希望根据表单中用户输入的图像宽度和高度,获取宽高比。例如,如果用户输入1024x768的图像,则应该得到4:3的宽高比。但是,我无论如何都找不到一个在PHP或Javascript中可用的公式示例,可以基于已知的宽度和高度来计算宽高比并将其插入变量中。
我简直不敢相信找不到这个公式。我正在使用一个名为SLIR的PHP脚本来调整图像大小。脚本要求指定一个用于裁剪的宽高比。我希望根据表单中用户输入的图像宽度和高度,获取宽高比。例如,如果用户输入1024x768的图像,则应该得到4:3的宽高比。但是,我无论如何都找不到一个在PHP或Javascript中可用的公式示例,可以基于已知的宽度和高度来计算宽高比并将其插入变量中。
要获得宽高比,只需像分数一样简化宽度和高度,例如:
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);
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);
}
331:220
,而期望的是6:4
? - Tim Bogdanov你不需要进行任何计算。
仅仅因为它说是长宽比,并不意味着它必须是一组有限的常用比例之一。它可以是由冒号分隔的任意一对数字。
引用自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
。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/
<?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);