2012-03-16 70 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); 
相关问题