php跟据图像中心生成缩略图thumb

如果一张长方形的图像,不管是立像还是卧像,可以跟据图像裁剪成一个正方形,再生成一个缩略图。

//from yiyou.org fy@yiyou.org
function cut2thumbnail($src_file,$dsc_file,$width,$height){
        if(!file_exists($src_file)){
            return false;
        }
        if($width <=0||$height <=0){
            return false;
        }
        $imagetype=  exif_imagetype($src_file);

        $src_img ='';
        switch ($imagetype){
            case IMAGETYPE_PNG:
                $src_img=imagecreatefrompng($src_file);
                break;
            case IMAGETYPE_JPEG:
                $src_img=  imagecreatefromjpeg($src_file); 
                break;
            case IMAGETYPE_BMP:
                $src_img=ImageCreateFromBMP($src_file);
                break;
            default:
                return false;
                break;
        }
        list($src_width,$src_height)=  getimagesize($src_file);
        //如果原图比请求的图像还要小
        if($src_width < $width || $src_height < $height){
            @copy($src_file, $dsc_file);
            return true;
        }
        
        
        $target_image  = imagecreatetruecolor($width,$height);//目标缩小后的图像
        
        $cropped_img=$src_img; //如果$cropped_image未改变,说明自身是正方型
        
        if($src_width > $src_height){ //宽大于高
            $diff=$src_width-$src_height; //差异
            $one_part =floor($diff/2); //取中间
            $cropped_img=  imagecreatetruecolor($src_height, $src_height);
            imagecopy($cropped_img,$src_img,0,0,$one_part,0,$src_height,$src_height);
        }
        if($src_width < $src_height){ //宽小于高
            $diff=$src_height-$src_width; //差异
            $one_part =floor($diff/2); //取中间
            $cropped_img=  imagecreatetruecolor($src_width, $src_width);
            imagecopy($cropped_img,$src_img,0,0,0,$one_part,$src_width,$src_width);
        }
        
        $cropped_width=imagesx($cropped_img);
        $cropped_height=imagesy ($cropped_img);
        
        imagecopyresampled($target_image, $cropped_img, 0, 0, 0, 0, $width, $height, $cropped_width, $cropped_height);

        switch ($imagetype){
            case IMAGETYPE_PNG:
                imagepng($target_image,$dsc_file);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($target_image, $dsc_file,90);
                break;
            case IMAGETYPE_BMP:
                imagejpeg($target_image,$dsc_file); 
                break;
        }
        return true;
        //imagedestroy($src_img);
        //imagedestroy($cropped_img);
        //imagedestroy($target_image);
}