简体   繁体   English

计算正确减少比例的照片尺寸在php中的宽度和高度?

[英]Calculate correct reduced in proportion photo size in width and height in php?

I have 2 variables available about a photo i'm importing, width and height.(I could use imagesx etc, but i'm importing in bulk and it takes way too long) 我有2个有关我要导入的照片的宽度,高度和变量。(我可以使用imagesx等,但是我要成批导入,它花费的时间太长了)

eg.. 例如..

$w = 720;
$h = 540;

How can I workout the correct height for the photo if I say the max width is 180px, I know the correct height should be 135px (on a standard landscape photo). 如果我说最大宽度为180px,我知道正确的高度应该为135px(在标准风景照片上),那么如何为照片设置正确的高度。 But the starting width and height i'm given will change depending on the photo. 但是我给出的起始宽度和高度将根据照片而变化。

Keeping the image in proportion what calculation do I need to do to workout the reduced width and height? 保持图像成比例我需要做哪些计算才能锻炼减小的宽度和高度?

Final result will be in pixels so can not have any decimal places. 最终结果将以像素为单位,因此不能有任何小数位。

(I do not actually need to re-size the photo, just calculate the size.) (我实际上不需要调整照片的大小,只需计算大小即可。)

Thanks in advance :) 提前致谢 :)

And this is the javascript version of @fire's answer 这是@fire答案的javascript版本

scaleDimensions : function(orig_width, orig_height, max_width, max_height) {
    if (orig_width < max_width && orig_height < max_height) {
        return [orig_width, orig_height];
    }

    var ratiow = max_width / orig_width;
    var ratioh = max_height / orig_height;
    var ratio = Math.min(ratiow, ratioh);
    var width = (ratio * orig_width).toFixed(0);
    var height = (ratio * orig_height).toFixed(0);
    return [width, height];
}

Here's one I use: 这是我使用的一个:

function scaleDimensions($orig_width, $orig_height, $max_width, $max_height) {
    if ($orig_width < $max_width && $orig_height < $max_height) {
        return array($orig_width, $orig_height);
    }

    $ratiow = $max_width / $orig_width;
    $ratioh = $max_height / $orig_height;
    $ratio = min($ratiow, $ratioh);
    $width = intval($ratio * $orig_width);
    $height = intval($ratio * $orig_height);
    return array($width, $height);
}

Usage: 用法:

list($width, $height) = scaleDimensions($w, $h, 180, 135);
720x = 540 * 180

It is a simple cross-multiplying rule. 这是一个简单的交叉乘法规则。 Then round the numbers to get rid of the decimal portion. 然后四舍五入数字以除去小数部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM