如何在运行时使用PHP调整图像大小

时间:2013-07-12 12:33:48

标签: php image performance time resize

您可以使用PHP在运行时调整图像大小:

public static function resize_img($srcimg,$dest_img,$max_width=0,$max_height=0)  {


    $save = $dest_img;
    $src = null;
    $source_pic = $srcimg;

    $imageinfo = getimagesize($source_pic);

    //print_r($imageinfo);die;
    switch($imageinfo['mime'])
    {
     case 'image/png':
     $src = imagecreatefrompng($source_pic);
     break;
     case 'image/jpeg':
     $src = imagecreatefromjpeg($source_pic);
     break;
     case 'image/gif':
     $src = imagecreatefromgif($source_pic);
     break;
     case 'image/x-ms-bmp':
     $src = imagecreatefrombmp($source_pic);
     break; 
    }

      list($width,$height) = getimagesize($source_pic);

      $x_ratio = $max_width / $width;
      $y_ratio = $max_height / $height;

      if( ($width <= $max_width) && ($height <= $max_height) ){
       $tn_width = $width;
       $tn_height = $height;
      }
      elseif($y_ratio == 0){
       $tn_height = ceil($x_ratio * $height);
       $tn_width = $max_width;
      }
      elseif($x_ratio == 0){
       $tn_width = ceil($y_ratio * $width);
       $tn_height = $max_height;
      }
      elseif (($x_ratio * $height) < $max_height){
       $tn_height = ceil($x_ratio * $height);
       $tn_width = $max_width;
      }
      else{
       $tn_width = ceil($y_ratio * $width);
       $tn_height = $max_height;
      }

     // $ext = strtolower(array_pop(explode(".", $srcimg)));
       $ext=substr($srcimg,-3,3);
      //ini_set('memory_limit', '32M');

      $tmp=imagecreatetruecolor($tn_width,$tn_height);
      //print_r($tmp.$src);die;

      imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

      if(($ext=="jpg") || ($ext=="jpeg")) 
      { 
        $ye = imagejpeg($tmp, $save, 100) ; 
      }

      if($ext=="gif"){ imagegif($tmp, $save) ;  }
      if($ext=="bmp"){ imagebmp($tmp, $save) ;  }
      if($ext=="png"){
        //imagecolortransparent($tmp, imagecolorallocate($tmp,0,0,0));
        imagepng($tmp, $save, 9) ;
        }

}   

$this->resize_img($source_path_with_name,$dest_img2,83,83); //83x83 small Profile Images

1 个答案:

答案 0 :(得分:1)

不是你想要的答案,但这是一个可能有帮助的好课程。 SimpleImage https://github.com/claviska/SimpleImage