天天看點

thinkphp 圖檔上傳生成縮略圖

<?php
namespace Admin\Controller;
use Think\Controller;
class GoodsController extends Controller {
	public $gm;
	public function __construct(){
		parent::__construct();//繼承父類的構造方法
		$this->gm=D('goods');

	}
    public function goodsadd(){
    	  if(IS_POST){
    	  	  if(!$this->gm->create($_POST)){
    	  	  	echo $this->gm->getError();
    	  	  	exit;
    	  	  }

                $upload = new \Think\Upload();// 執行個體化上傳類
                $upload->maxSize = 3145728 ;// 設定附件上傳大小
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳類型
                $upload->rootPath = './Upload/'; // 設定附件上傳根目錄
                $upload->savePath = ''; // 設定附件上傳(子)目錄
                // 上傳檔案
                $info = $upload->upload();
                if(!$info) {// 上傳錯誤提示錯誤資訊
                $this->error($upload->getError());
                }else{// 上傳成功
               $img_path1='./Upload/'.$info['goods_img']['savepath'];
               $img_path2=$info['goods_img']['savename'];//儲存路徑
            
                $image = new \Think\Image();
                $image->open($img_path1.$img_path2);//打開原圖
                // 按照原圖的比例生成一個最大為150*150的縮略圖并儲存為thumb.jpg
                $img_xiao='./Upload/thumb/'.$img_path2;//縮略圖生成的路徑
                $image->thumb(150, 150)->save($img_xiao);//縮略圖按照150的比例儲存
                $this->gm->thumb_img=$img_xiao;//資料庫中thumb_img字段的值來自于$img_xiao
               $this->gm->goods_img=$img_path1.$img_path2;//資料庫中goods_img字段的值來自于$img_path;

                }
    	  	 $this->gm->add();
    	  }
        $this->display();
    }
}