php 压缩各格式图片,处理png格式图片背景黑色问题

时间:2022-10-23 23:49:51
    //压缩图片
//$srcFile 文件名
//$percent压缩比
//$quality图片质量
    function pictumb($srcFile,$percent,$quality){
        $dstFile = $srcFile;//保留名字
        //header('Content-Type: image/jpeg');
        // 获取新的尺寸
        list($width, $height) = getimagesize($srcFile);
        if ($width>600){
            $new_width = $width / $percent;
            $new_height = $height / $percent;
        }else{
            $new_width =$width;
            $new_height = $height;
        }
            // 重新取样
            $image_p = imagecreatetruecolor($new_width, $new_height);
            //设置颜色
            $color=imagecolorallocate($image_p,255,255,255); 
            imagecolortransparent($image_p,$color); 
            imagefill($image_p,0,0,$color); 
            //获取格式
            $format=substr($srcFile,strrpos($srcFile, '.'));
            switch ($format) {
                case '.png':
                    $image=imagecreatefrompng($srcFile);
                    break;
                case '.jpeg':
                    $image=imagecreatefromjpeg($srcFile);
                    break;
                case '.bmp':
                    $image=imagecreatefromwbmp($srcFile);
                    break;
                case '.gif':
                    $image=imagecreatefromgif($srcFile);
                    break;
                default:
                     $image=imagecreatefromjpeg($srcFile);
                    break;
            }
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            chmod($srcFile,0777);//unlink函数要求对删除的图片有777的权限
            unlink($srcFile);//先删除图片,在进行保存
            // 输出
            switch ($format) {
                case '.png':
                    imagepng($image_p,$dstFile);
                    break;
                case '.jpeg':
                    imagejpeg($image_p,$dstFile, $quality);
                    break;
                case '.bmp':
                    imagewbmp($image_p,$dstFile);
                    break;
                case '.gif':
                    imagegif( $image_p,$dstFile);
                    break;
                default:
                     imagejpeg($image_p,$dstFile,$quality);
                    break;
            }
    }