PHP后台图片的等比缩放

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

//产品多图片上传
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"=>"上传有误,清检查服务器配置!"));
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_31570703/article/details/78223465
今日推荐