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

时间:2012-03-16 10:39:54

标签: php png gd jpeg

这是我刚写的代码。它需要一个图像作物然后创建一个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;

    }

1 个答案:

答案 0 :(得分:1)

我相信您需要在使用imagecreatetruecolor创建图片后使用imagesavealpha()保存Alpha通道。

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