在PHP中查找图像的新比例尺寸


Find new proportional dimensions of an image in PHP

我有一个网站,我想上传一张图片并调整它的大小,因为我必须把它放在一个有一定尺寸的div中。

例如max-width是200px max-height是100px

我要上传图像并检查宽度和高度,如果它们大于max-width或max-height我要找到图像的大小以保持在该div内

如何按比例调整图像的大小?我只想在div的底边设置新的宽度和高度200px*100px

这是我的脚本:

            if(move_uploaded_file($tmp, $path.$actual_image_name))
            {
                list($width, $height, $type, $attr) = getimagesize($tmp);
                if($width>200){
                    //too large I want to resize
                }
                if($height>100){
                    //too height I want to resize
                }
                echo(base_url().$path.$actual_image_name);
            }

您可以使用下面的函数来保持在边界框内。如200 x200型。只需要输入filelocation和最大宽度和高度。它将返回一个数组,其中$ar[0]是新的宽度,$ar[1]是新的高度。

它是完整地写出来的,这样你可以理解数学。

<?php
function returnSize($maxW,$maxH,$img) {
    $maxW = ($maxW>0 && is_numeric($maxW)) ? $maxW : 0;
    $maxH = ($maxH>0 && is_numeric($maxH)) ? $maxH : 0;
    // File and new size
    if (!file_exists($img)) {
        $size[0]=0;
        $size[1]=0;
        return $size;
    }
    $size = getimagesize($img);
    if ($maxW>0 && $maxH>0) {
        if ($size[0]>$maxW) {
            $scaleW = $maxW / $size[0];
        } else {
            $scaleW = 1;
        }
        if ($size[1]>$maxH) {
            $scaleH = $maxH / $size[1];
        } else {
            $scaleH = 1;
        }
        if ($scaleW > $scaleH) {
            $fileW = $size[0] * $scaleH;
            $fileH = $size[1] * $scaleH;
        } else {
            $fileW = $size[0] * $scaleW;
            $fileH = $size[1] * $scaleW;
        }
    } else if ($maxW>0) {
        if ($size[0]>$maxW) {
            $scaleW = $maxW / $size[0];
        } else {
            $scaleW = 1;
        }
        $fileW = $size[0] * $scaleW;
        $fileH = $size[1] * $scaleW;
    } else if ($maxH>0) {
        if ($size[1]>$maxH) {
            $scaleH = $maxH / $size[1];
        } else {
            $scaleH = 1;
        }
        $fileW = $size[0] * $scaleH;
        $fileH = $size[1] * $scaleH;
    } else {
        $fileW = $size[0];
        $fileH = $size[1];
    }
    $size[0] = $fileW;
    $size[1] = $fileH;
    return $size;
}
?>

这是计算比率的最基本的方法(保持不变的比例):

if($width>200){
    $percentage = (200/$width)*100; //Work out percentage
    $newWidth = 200; // Set new width to max width
    $newHeight = round($height*$percentage); //Multiply original height by percentage
}
else if($height>100){
    $percentage = (100/$height)*100; //Work out percentage
    $newHeight = 100; // Set new height to max height
    $newWidth = round($width*$percentage); //Multiply original width by percentage
}

我使用round()来确保您收到仅整数的新维度

以下是一些选项…

第一个:http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/

和第二个:http://www.sitepoint.com/image-resizing-php/-所有的数学工作已经完成