本文執行個體講述了thinkPHP實現上傳圖片及產生縮圖功能。分享給大家供大家參考,具體如下:
記錄一下在thinkPHP上傳圖片的方法(Upload)和產生縮圖(Image)的方法.
html頁面form中必須加enctype="multipart/form-data"
<form action="SELF" method="post" enctype="multipart/form-data"> <table width="100%"class="cont"> <tr> <td>照片:</td> <td width="20%"><input type="file" name="pic" id="pic" /></td> <td colspan="3"><input class="btn" type="submit" value="提交" /></td> <td> </td> </tr> </table></form>
php代碼
<?phpnamespace Admin\Controller;use Org\Util\Date;use Think\Controller;use Think\Image;use Think\Upload;class UserController extends Controller { public function add(){ $user = M('user'); if(!empty($_POST)){ $user = $user->create(); //判斷傳入的圖片有沒有問題 if($_FILES['pic']['error'] == 0){ $config = array( 'rootPath' => './Application/public/image/' // 設定圖片儲存路徑 ); //new一個上傳模型 $upload = new Upload($config); //上傳圖片 $pic = $upload->uploadOne($_FILES['pic']); //將圖片儲存到資料庫中 $user['big_pic'] = $pic['savepath'].$pic['savename']; //產生縮圖 $img = new Image(); //大圖片的路徑 $big_img = $upload->rootPath.$user['big_pic']; //開啟大圖片 $img->open($big_img); //設定圖片大小 $img->thumb(200,300); //設定絕對路徑 $small_img = $upload->rootPath.$pic['savepath'].'small_'.$pic['savename']; //儲存 $img->save($small_img); //將圖片名稱存入資料庫 $user['img'] = $pic['savepath'].'small_'.$pic['savename']; } $user['create_date'] = date("Y-m-d H:i:s"); $msg = "添加失敗"; if(M("user")->add($user)) $msg = "添加成功"; $this->redirect(show_list,null,3,$msg); } $this->display(); }