图片压缩

/**
 * 2018-05-24 15:19:26
 * 图片生成缩略图,并且返回原图片_thumb的文件路径
 */
function picReplace($file ='/uploads/download/2018-01-19/5a61bf55dfc77.jpg'){
    $file_real_path = ROOT_PATH.'public'.$file;//halt($file_real_path);
    //压缩图片,宽度指定300,高度等比
    if($file && file_exists($file_real_path)){
        // 获取文件尾缀
        // $path = pathinfo($file,PATHINFO_EXTENSION );halt($path);
        $file_name = explode('.', $file);
        $thumb_name = $file_name[0].'_thumb';
        //缩略图真实路径
        $thumb_real_path = ROOT_PATH.'/public'.$thumb_name.".{$file_name[1]}";
        if(!file_exists($thumb_real_path)){
            list($width, $height) = getimagesize($file_real_path); //获取原图尺寸
            $houzhui = getimagesize($file_real_path)['mime'];
            $houzhui = substr(strrchr($houzhui, '/'), 1);   
            //缩放尺寸
            $newwidth = 100;
            $percent = $newwidth/$width;  //图片压缩比
            $newheight = $height * $percent;
            switch ($houzhui) {
                case 'jpeg':
                    $src_im = imagecreatefromjpeg($file_real_path);
                    break;
                case 'gif':
                    $src_im = imagecreatefromgif($file_real_path);
                    break;
                case 'png':
                    $src_im = imagecreatefrompng($file_real_path); 
                    break;
                default:
                    $src_im = imagecreatefromjpeg($file_real_path);
                    break;
            }
            
            $dst_im = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            imagepng($dst_im, $thumb_real_path); //输出压缩后的图片
            imagedestroy($dst_im);
            imagedestroy($src_im);
        }
        //替换原来的图片路径
        return $thumb_name.".{$file_name[1]}";
    }else{
        return $file;
    }
}

缩略图小结

1.is_file(),is_dir(),file_exists()三个函数的用法
  • file_exists()判断文件或者文件夹是否存在
  • 文件/文件夹存在,is_file()/is_dir()比file_exists()快n倍
  • 文件/文件夹不存在,file_exists()比is_file()/is_dir()快
2.获取文件后缀
  • pathinfo($file,PATHINFO_EXTENSION )
  • substr(strrchr($file,'.'),1)
  • explode('.',file)[1]
3.获取文件类型
  • 文件名后缀被篡改时,调用PHP的GD库函数获取文件MIME属性
$mime = getimagesize($file)['mime'];
$extension = substr($extension,strrpos($mime,'/')+1);

你可能感兴趣的:(图片压缩)