PHP根据指定宽或高计算比例

<?php
/**
 * 根据指定宽或高计算比例
 */
function resizeImage($pic_width, $pic_height, $maxwidth,$maxheight)
{
    $CI =& get_instance();

    if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
    {
        if ($maxwidth && $pic_width > $maxwidth)
        {
            $widthratio = $maxwidth / $pic_width;
            $resizewidth_tag = true;
        }

        if ($maxheight && $pic_height > $maxheight)
        {
            $heightratio = $maxheight / $pic_height;
            $resizeheight_tag = true;
        }

        if ($resizewidth_tag && $resizeheight_tag)
        {
            // 指定宽度,如需根据高度计算比例,则修改成$widthratio>$heightratio
            if ($widthratio < $heightratio) $ratio = $widthratio;
            else $ratio = $heightratio;
        }

        if ($resizewidth_tag && !$resizeheight_tag) $ratio = $widthratio;
        if ($resizeheight_tag && !$resizewidth_tag) $ratio = $heightratio;

        $newwidth = $pic_width * $ratio;
        $newheight = $pic_height * $ratio;
        
        return array(
            'newwidth' => $newwidth,
            'newheight' => $newheight,
        );
    }
    
    return FALSE;
}
?>

 

PHP按照比例计算图片大小

<?php
/**
 * 按照比例计算图片大小
 */
function chang_image_size($img_w, $img_h, $max_w, $max_h)
{
    $CI =& get_instance();
    
    // 计算缩放比例
    $w_ratio = $max_w / $img_w;
    $h_ratio = $max_h / $img_h;
    
    // 决定处理后的图片宽和高
    if ( ($img_w <= $max_w) && ($img_h <= $max_h) )
    {
        $tn['w'] = $img_w;
        $tn['h'] = $img_h;
    }
    elseif (($w_ratio * $img_h) < $max_h)
    {
        $tn['w'] = $max_w;
        $tn['h'] = ceil($w_ratio * $img_h);
    }
    else 
    {
        $tn['w'] = ceil($h_ratio * $img_w);
        $tn['h'] = $max_h;
    }
    
    $tn['rc_w'] = $img_w;
    $tn['rc_h'] = $img_h;
    
    return $tn ;
}
?>