tp5 生成縮略圖片


我先說下我的思路,先把正常圖片存到服務器,再通過代碼將服務器上的大圖壓縮,生成新的小圖替代大圖

下面上代碼

前台HTML代碼

<div class="upload-btn">
	<input class="pic-ipt" type="file" accept="image/*" />
</div>

script代碼

 

function upload_img(cid){
			var formData = new FormData();
			formData.append("file", $(this).get(0).files[0]);
		    $.ajax({
		        url:'./upload_photo',
		        type:'POST',
		        data:formData,
		        cache: false,
		        contentType: false,
		        processData: false,
		        success:function(data){
		        	console.log(data);
		        }
		    });
		}

php代碼   

/**
     * 上傳
     */
    public function upload_photo(){
        $file = $this->request->file('file');
        //生成縮略圖
        // $file = \think\Image::open($file);
        // $test = $file->thumb(400, 400)->save(ROOT_PATH . 'public' . DS . 'uploads/'.time().'.png');
        // return ['code'=>2,'error'=>$test->getFilename()];
                if(!empty($file)){
                    // 移動到框架應用根目錄/public/uploads/ 目錄下
                    $info = $file->validate(['size'=>4145728,'ext'=>'jpg,png,gif,jpeg'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                    $error = $file->getError();
                    // return ['code'=>2,'error'=>$error];
                    //驗證文件后綴后大小
                    if($error){
                        return ['code'=>2,'error'=>$error];
                        // dump($error);exit;
                    }
                    if($info){
                        // 成功上傳后 獲取上傳信息
                        // 輸出 jpg
                        $info->getExtension();
                        // 輸出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        $info->getSaveName();
                        // 輸出 42a79759f284b767dfcb2a0197904287.jpg
                        $photo = $info->getFilename();
                        $imgurl = './public/uploads/'.$photo;//原大圖路徑,當時我獲取的時候費了不少時間
                        $image = \think\Image::open($imgurl);
                        $image->thumb(400, 400,1)->save($imgurl);//生成縮略圖、刪除原圖
                    }else{
                        // 上傳失敗獲取錯誤信息
                        $file->getError();
                    }
                }else{
                    $photo = '';
                }
        if($photo !== ''){
            return ['code'=>1,'msg'=>'成功','photo'=>$photo];
        }else{
            return ['code'=>404,'msg'=>'失敗'];
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM