PHP后台图片的等比缩放

来源:互联网 发布:整理数据 英语 编辑:程序博客网 时间:2024/04/28 23:34

//图片上传实现等比缩放

//产品多图片上传public function index(){    $typeArr = array("jpg", "png", "gif");//允许上传文件格式    $path = "./uploads/img/";//上传路径    if (isset($_POST)) {        $name = $_FILES['file']['name'];        $size = $_FILES['file']['size'];        $name_tmp = $_FILES['file']['tmp_name'];        if (empty($name)) {            echo json_encode(array("error"=>"您还未选择图片"));exit;        }        $type = strtolower(substr(strrchr($name, '.'), 1)); //获取文件类型        if (!in_array($type, $typeArr)) {            echo json_encode(array("error"=>"请上传jpg,pnggif类型的图片!"));exit;        }        if ($size > (2*1024*1024)) {            echo json_encode(array("error"=>"图片大小已超过2MB"));exit;        }        $image = \think\Image::open(request()->file('file'));        $type = $image->type();        //获取图片的高度和宽度        $width = $image->width();        $height = $image->height();        $file = date("Ymd",time());        $fileName = './uploads/thums/'.$file;        if (!is_dir($fileName)) mkdir($fileName, 0777);        $imgName = md5(uniqid(rand())).'.'.$type;        $pathurl = $fileName.'/'.$imgName;//路径+图片名称        if(($width/$height) == 1){  //当当前图片的比例大于目标图片的比例 则按照宽度进行压缩,实现高度等比缩放            $result = $image->thumb(560,560,\think\Image::THUMB_SCALING)->save($pathurl);        }else{            $result = $image->thumb(560,560,\think\Image::THUMB_FILLED)->save($pathurl);        }        if($result){            echo json_encode(array("error"=>"0","pic"=>substr($pathurl,1),"name"=>$imgName));        }else{            echo json_encode(array("error"=>"上传有误,清检查服务器配置!"));        }    }}

原创粉丝点击