thinkPHP实现上传图片及生成缩略图功能示例

时间:2022-04-18 08:14:37

本文实例讲述了thinkPHP实现上传图片及生成缩略图功能。分享给大家供大家参考,具体如下:

记录一下在thinkPHP上传图片的方法(Upload)和生成缩略图(Image)的方法.

html页面form中必须加enctype="multipart/form-data"

?
1
2
3
4
5
6
7
8
9
10
<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>&nbsp;</td>
    </tr>
  </table>
</form>

php代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
namespace 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();
  }

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

原文链接:http://blog.csdn.net/qq_22793991/article/details/53710252