2012-03-16 66 views
1

這是我剛寫的代碼。它需要一個圖像作物,然後創建一個jpg圖像。 如果我給它一個JPG文件,它工作正常,但不適用於PNG(透明)圖像。它只是使黑色背景的空白圖像。調整PNG大小並將其轉換爲JPG格式的PHP

我第一次使用GD庫,所以我的錯誤是什麼?

public function crop_thumb($file, $width=150, $height=150){ 

     $file_type = get_file_extension($file); 
     $file_name = get_file_name($file); 

     $original_image_size = getimagesize(_dir_uploads_.$file); 
     $original_width = $original_image_size[0]; 
     $original_height = $original_image_size[1]; 

     if($file_type == 'jpg'){ 
      $original_image_gd = imagecreatefromjpeg(_dir_uploads_.$file); 
     }elseif($file_type == 'gif'){ 
      $original_image_gd = imagecreatefromgif(_dir_uploads_.$file); 
     }elseif($file_type == 'png'){ 
      $original_image_gd = imagecreatefrompng(_dir_uploads_.$file); 
     } 

     $cropped_image_gd = imagecreatetruecolor($width, $height); 

     $wm = $original_width/$width; 
     $hm = $original_height/$height; 

     $h_height = $height/2; 
     $w_height = $width/2; 

     if($original_width > $original_height){ 

      $adjusted_width = $original_width/$hm; 
      $half_width = $adjusted_width/2; 
      $int_width = $half_width - $w_height; 

      imagecopyresampled($cropped_image_gd ,$original_image_gd ,-$int_width,0,0,0, $adjusted_width, $height, $original_width , $original_height); 

     }elseif(($original_width < $original_height) || ($original_width == $original_height)){ 

      $adjusted_height = $original_height/$wm; 
      $half_height = $adjusted_height/2; 
      $int_height = $half_height - $h_height; 

      imagecopyresampled($cropped_image_gd , $original_image_gd ,0,-$int_height,0,0, $width, $adjusted_height, $original_width , $original_height); 

     }else{ 

      imagecopyresampled($cropped_image_gd , $original_image_gd ,0,0,0,0, $width, $height, $original_width , $original_height); 

     } 

     $create = imagejpeg($cropped_image_gd, _dir_uploads_.$file_name."-".$width."x".$height.".jpg"); 

     return ($create) ? true : false; 

    } 

回答

1

我相信你需要使用imagesavealpha()創建使用imagecreatetruecolor圖像後保存alpha通道。

$cropped_image_gd = imagecreatetruecolor($width, $height); 
imagealphablending($cropped_image_gd, false); 
imagesavelalpha($cropped_image_gd, true); 
相關問題