欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-14 15:13:55
本文实例讲述了php实现将上传图片自动缩放到指定分辨率,并保持清晰度封装类。分享给大家供大家参考,具体如下: class autoimage{ privat...

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

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相关内容感兴趣的读者可查看本站专题:《php图形与图片操作技巧汇总》、《php数组(array)操作技巧大全》、《php数据结构与算法教程》、《php程序设计算法总结》、《php数学运算技巧总结》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总

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