Example of Uploading Pictures and Generating Thumbnails by thinkPHP

  • 2021-08-12 02:11:31
  • OfStack

This paper describes the functions of uploading pictures and generating thumbnails by thinkPHP. Share it for your reference, as follows:

A method for uploading a picture on thinkPHP (Upload) and a method for generating a thumbnail (Image) under Record 1.

enctype= "multipart/form-data" must be added to form on html page


<form action="__SELF__" method="post" enctype="multipart/form-data">
 <table width="100%"class="cont">
   <tr>
   <td> Photo: </td>
   <td width="20%"><input type="file" name="pic" id="pic" /></td>
   <td colspan="3"><input class="btn" type="submit" value=" Submit " /></td>
   <td>&nbsp;</td>
    </tr>
  </table>
</form>

php code


<?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();
      // Determine if there is any problem with the incoming picture 
      if($_FILES['pic']['error'] == 0){
        $config = array(
          'rootPath'  => './Application/public/image/' //  Set the picture saving path 
        );
        //new1 Upload model 
        $upload = new Upload($config);
        // Upload pictures 
        $pic = $upload->uploadOne($_FILES['pic']);
        // Save pictures to a database 
        $user['big_pic'] = $pic['savepath'].$pic['savename'];
        // Generate thumbnails 
        $img = new Image();
        // Path of large picture 
        $big_img = $upload->rootPath.$user['big_pic'];
        // Open a large picture 
        $img->open($big_img);
        // Set the picture size 
        $img->thumb(200,300);
        // Set Absolute Path 
        $small_img = $upload->rootPath.$pic['savepath'].'small_'.$pic['savename'];
        // Save 
        $img->save($small_img);
        // Save the picture name in the database 
        $user['img'] = $pic['savepath'].'small_'.$pic['savename'];
      }
      $user['create_date'] = date("Y-m-d H:i:s");
      $msg = " Add failed ";
      if(M("user")->add($user))
        $msg = " Successful addition ";
      $this->redirect(show_list,null,3,$msg);
    }
    $this->display();
  }

Readers who are interested in thinkPHP can check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: