php简单的图片缩放类(二)

弄好了就开始优化这个类

header("content-type:text/html;charset=utf-8");
class Image{
    
    

    public function thumb($img,$dstx,$dsty,$type){
    
    
        echo '我是图片缩放';
        
    }

}
$img = new Image();
$img->thumb("uploads/ong.jpg",560,250,'png');

大致的框架弄好之后,开始具化

header('Content-Type: image/jpeg');
class Image{
    
    

    public function thumb($img,$dstx,$dsty,$pre){
    
    
        $info = getimagesize($img);

        $srcx = $info[0];
        $srcy = $info[1];

        $scale = max($srcx/$dstx,$srcy/$dsty);

        $x = floor($srcx/$scale);
        $y = floor($srcy/$scale);

        //暂时就列常用的
        switch ($info[2]){
    
    
            case 1:
                //gif图
                break;
            case 2:
                //jpg图
                $srcimg = imagecreatefromjpeg($img);
                break;
            case 3:
                //png图
                $srcimg = imagecreatefrompng($img);
                break;
        }
        $dstimg = imagecreatetruecolor($x,$y);
        $d = dirname($img);
        //这里是获取文件除后缀的名字
        $filename = basename($img);
        $filename = explode('.',$filename);
        $filename = array_splice($filename,0,1);
        $filename = join('',$filename);

        imagecopyresampled($dstimg,$srcimg,0,0,0,0,$x,$y,$srcx,$srcy);
        //根据需要的后缀名来生成图片
        switch ($pre){
    
    
            case 'jpg':
                $th = $d.'/'.'thumb_'.time().'_'.rand(10,99).'_'.$filename.'.'.$pre;
                if(imagejpeg($dstimg,$th)){
    
    
                    echo $pre.'图像生成成功';
                }
                imagedestroy($dstimg);
                imagedestroy($srcimg);
                break;
            case 'png':
                $th = $d.'/'.'thumb_'.time().'_'.rand(10,99).'_'.$filename.'.'.$pre;
                if(imagepng($dstimg,$th)){
    
    
                    echo $pre.'图像生成成功';
                }
                imagedestroy($dstimg);
                imagedestroy($srcimg);
                break;
        }

    }
}

$im = new Image();
$im->thumb("uploads/a.jpg",400,150,'png');

图片生成
看目录下,确实已经出来了
ok,这样的话简单的图片缩放类就完成,看完的大佬们动动小手点个赞呗

猜你喜欢

转载自blog.csdn.net/weixin_44088587/article/details/112591848
今日推荐