PHP图片等比例缩放生成缩略图函数分享

时间:2022-10-07 13:58:20

复制代码 代码如下:


<?php
    /*
    *@im     //需要缩放的图片资源
    *@filetype //制作的缩略图文件类型
    *@dstimW   //缩放的图片的宽度
    *@dstimH  //缩放的图片的高度
    *@thumbname //缩略图文件名字
function makethumb($im,$dstimW,$dstimH,$thumbname ,$filetype){
            //获取im的宽度和高度
        $pic_W=imagesx($im);
        $pic_H=imagesy($im);
        $arr = array();
            swith($filetype){
                case 'jpg':
                        $arr[$filetype]="imagejpeg";
                        break;
                case 'png';
                        $arr[$filetype]="imagepng";
                        break;
                case 'jif';
                        $arr[$filetype]="imagegif";
                }
        if(($dstimgW && $dstimgW<$pic_W) || ($dstimgH && $dstimgH<$pic_H) ){
                if($dstimgW && $dstimgW<$pic_W){
                    $dsimgWratio = $dstimgW / $pic_w;
                    $resizereagW =true;

 

                }
                if($dstimgH && $ $dstimgH <$pic_H){
                    $dsimgHratio = $dstimgH/$pic_H;
                    $resizerreagH =true;
                }
                //缩略图宽高和原图宽高比,取最小的那个
                if($resizereagW && $resizerreagH){
                    if($dsimgWratio<$dsimgHratio)
                        $radio = $dsimgWratio;
                    else
                        $radio = $dsimgHratio;     
                }
                if($resizereagW && !$resizerreagH ){
                        $radio = $dsimgWratio;
                }
                if(!$resizereagW && $resizerreagH){
                       $radio = $dsimgHratio ;
                }
                $imgnewW = $pic_W * $radio;
                $imgnewH = $pic_H * $radio;
                if(function_exists("imgcopyresampled")){
                      //创建目标资源画布
                    $dst = imagecreatetruecolor ($imgnewW, $imgnewH);
                    imagecopyresampled ($dst,$im,0,0,0,0,$imgnewW,$imgnewH,$pic_W,$pic_H);
                }else{
             $dst=imagecreate($imgnewW, $imgnewH);
             imagecopyresized ($dst, $im,0,0,0,0,$imgnewW,$imgnewH,$imgnewH,$pic_W,$pic_H);
                }

        $arr[$filetype]($dst,$thumbname.".$filetype");
        imagedestroy ($dst);
    }else{//缩略图自身的宽和高已经大于了原图的宽和高
           //则缩略图的宽和缩略的高就是原图的宽和原图的高
         $arr[$filetype]($im,$thumbname.".$filetype");
         imagedestroy();
    }
}
?>