PHP实现将上传图片自动缩放到指定分辨率,并保持清晰度封装类示例

时间:2022-08-28 19:49:30

本文实例讲述了PHP实现将上传图片自动缩放到指定分辨率,并保持清晰度封装类。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class AutoImage{
  private $image;
  public function resize($src, $width, $height){
    //$src 就是 $_FILES['upload_image_file']['tmp_name']
    //$width和$height是指定的分辨率
    //如果想按指定比例放缩,可以将$width和$height改为$src的指定比例
    $this->image = $src;
    $info = getimagesize($src);//获取图片的真实宽、高、类型
    if($info[0] == $width && $info[1] == $height){
      //如果分辨率一样,直接返回原图
      return $src;
    }
    switch ($info['mime']){
      case 'image/jpeg':
        header('Content-Type:image/jpeg');
        $image_wp = imagecreatetruecolor($width, $height);
        $image_src = imagecreatefromjpeg($src);
        imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
        imagedestroy($image_src);
        imagejpeg($image_wp,$this->image);
        break;
      case 'image/png':
        header('Content-Type:image/png');
        $image_wp = imagecreatetruecolor($width, $height);
        $image_src = imagecreatefrompng($src);
        imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
        imagedestroy($image_src);
        imagejpeg($image_wp,$this->image);
        break;
      case 'image/gif':
        header('Content-Type:image/gif');
        $image_wp = imagecreatetruecolor($width, $height);
        $image_src = imagecreatefromgif($src);
        imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
        imagedestroy($image_src);
        imagejpeg($image_wp,$this->image);
        break;
    }
    return $this->image;
  }
}

希望本文所述对大家PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/ltx06/article/details/81627161