0

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

例如,我的最大宽度为 200 像素,最大高度为 100 像素

我想上传图像并检查宽度和高度,如果它们大于最大宽度或最大高度,我想找到图像的大小以保持在该 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);
            }
4

3 回答 3

1

这是计算比率的基础知识(保持持续规模):

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()确保您收到仅整数的新维度

于 2013-05-14T07:45:57.947 回答
1

您可以使用下面的函数留在边界框内。例如 200x200。只需发送文件位置和最大宽度和高度。它将返回一个数组,其中$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;
}
?>
于 2013-05-14T07:48:05.147 回答
0

以下是一些选项...

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

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

于 2013-05-14T07:45:27.100 回答