年紀大了有些事容易忘記... 所以.....

星期四, 4月 17, 2014

PHP 自動等比縮放圖片函式

//取圖片寬高並回傳適合寬高
 /*
  $org_height 原圖高
  $org_width 原圖寬
  $height 限制的高
  $width 限制的寬
  $autoResize 是否強制縮到寬高都在範圍內
  2014/4/17 @C Fixed
 */
 function getImageSize_resize($org_height='',$org_width='',$height='',$width='',$autoResize='N'){
  if(!$org_height || !$org_width){
   return FALSE;
  }
  
  $new_height = '';
  $new_width = '';

  $tmp_width = $org_width;//圖片寬度
  $tmp_height = $org_height;//圖片高度
  
  $ratio = 1;
  
  if(($width && $tmp_width > $width) || ($height && $tmp_height > $height))
  {
   if($width && $tmp_width > $width)
   {
    $width_ratio = $width/$tmp_width;
    $resize_width_tag = true;
   }
   
   if($height && $tmp_height > $height)
   {
    $height_ratio = $height/$tmp_height;
    $resize_height_tag = true;
   }
      
   if($resize_width_tag || $resize_height_tag)
   {
    if($width_ratio > $height_ratio)
    {
     $ratio = $width_ratio;
    }
    else
    {
     $ratio = $height_ratio;
    }
    
    if($resize_width_tag && !$resize_height_tag)
    {
     $ratio = $width_ratio;
    }
    
    if($resize_height_tag && !$resize_width_tag)
    {
     $ratio = $height_ratio;
    }

    $new_width = round($tmp_width*$ratio);
    $new_height = round($tmp_height*$ratio);

    if($autoResize=="Y")
    {
     if(($width && $new_width > $width) || ($height && $new_height > $height))
     {
      return $this->getImageSize_resize($new_height,$new_width,$height,$width,"Y");
     }
    }
    
    return array($tmp_width,$tmp_height,$new_width,$new_height);
   }
  }
  return array($tmp_width,$tmp_height,$new_width,$new_height);
 }