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

yipeiwu_com6年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

PHP框架性能测试报告

作为一个PHP开发者,而且是初创企业团队的技术开发者,选择开发框架是个很艰难的事情。 用ThinkPHP的话,招聘一个刚从培训机构出来的开发者就可以上手了,但是性能和后期代码解耦是个让人...

php urlencode()与urldecode()函数字符编码原理详解

php urlencode()与urldecode()函数字符编码原理详解

其原理就是把中文字符转换为十六进制并按某种规则进行字符串组合,实现字符的编码与解编码,保证URL数据传递过程中字符的完整性和兼容性,主要讨论中文字符的编码情况。 一,FireFox浏览器...

PHP函数shuffle()取数组若干个随机元素的方法分析

本文实例讲述了PHP函数shuffle()取数组若干个随机元素的方法。分享给大家供大家参考,具体如下: 有时候我们需要取数组中若干个随机元素(比如做随机推荐功能),那么PHP要如何实现呢...

php通过asort()给关联数组按照值排序的方法

本文实例讲述了php通过asort()给关联数组按照值排序的方法。分享给大家供大家参考。具体分析如下: php通过asort()给关联数组按照值排序,和sort的区别是,sort为数组中...

php中session垃圾回收机制

在PHP中,没有任何变量指向这个对象时,这个对象就成为垃圾。PHP会将其在内存中销毁;这是PHP的GC垃圾处理机制,防止内存溢出。 GC的工作就是扫描所有的Session信息,用当前时间...