调整PNG的大小并在PHP中转换为JPG图像


Resize PNG and convert to JPG image in PHP

这是我刚刚写的代码。它获取一个图像,将其裁剪,然后创建一个jpg图像。如果我给它一个jpg文件,它可以很好地工作,但不适用于png(透明)图像。它只是制作了一个黑色背景的空白图像。

我是第一次使用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;
    }

我认为在使用imagecreatetruecolor创建图像后,需要使用imagesavealpha()保存alpha通道。

$cropped_image_gd = imagecreatetruecolor($width, $height);
imagealphablending($cropped_image_gd, false);
imagesavelalpha($cropped_image_gd, true);