兼容性最強的PHP生成縮略圖的代碼

 

寫通用性程序考慮兼容性是很頭痛的事情,關於用PHP生成縮略圖的代碼很多,不過能完全兼容gd1.6和gd2.x,並能保證縮圖清晰性的代碼幾乎沒有,

以下代碼可以實現(感謝網友的分享):


function ImageResize($srcFile,$toW,$toH,$toFile="") 
{
   if($toFile==""){ $toFile = $srcFile; }
   $info = "";
   $data = GetImageSize($srcFile,$info);
   switch ($data[2]) 
   {
    case 1:
      if(!function_exists("imagecreatefromgif")){
       echo "你的GD庫不能使用GIF格式的圖片,請使用Jpeg或PNG格式!<a href='javascript:go(-1);'>返回</a>";
       exit();
      }
      $im = ImageCreateFromGIF($srcFile);
      break;
    case 2:
      if(!function_exists("imagecreatefromjpeg")){
       echo "你的GD庫不能使用jpeg格式的圖片,請使用其它格式的圖片!<a href='javascript:go(-1);'>返回</a>";
       exit();
      }
      $im = ImageCreateFromJpeg($srcFile);    
      break;
    case 3:
      $im = ImageCreateFromPNG($srcFile);    
      break;
  }
  $srcW=ImageSX($im);
  $srcH=ImageSY($im);
  $toWH=$toW/$toH;
  $srcWH=$srcW/$srcH;
  if($toWH<=$srcWH){
       $ftoW=$toW;
       $ftoH=$ftoW*($srcH/$srcW);
  }
  else{
      $ftoH=$toH;
      $ftoW=$ftoH*($srcW/$srcH);
  }    
  if($srcW>$toW||$srcH>$toH)
  {
     if(function_exists("imagecreatetruecolor")){
        @$ni = ImageCreateTrueColor($ftoW,$ftoH);
        if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
        else{
         $ni=ImageCreate($ftoW,$ftoH);
          ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
        }
     }else{
        $ni=ImageCreate($ftoW,$ftoH);
        ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
     }
     if(function_exists('imagejpeg')) ImageJpeg($ni,$toFile);
     else ImagePNG($ni,$toFile);
     ImageDestroy($ni);
  }
  ImageDestroy($im);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章