1. 程式人生 > >thinkphp上傳圖片並批量生成不同尺寸縮圖

thinkphp上傳圖片並批量生成不同尺寸縮圖

1、配置資訊

    //****************************各種型別圖片縮圖尺寸設定*************************//
    'IMAGES_THUMB_SIZE_SETTING'     =>array(
        'USER_HEADER'       =>array(   //使用者頭像縮圖大小
            '64*64'     =>'64*64',
            '32*32'     =>'32*32'
        ),
        'PHOTOS_HEADER'  =>'128*128',                       //圖片縮圖大小
        'EMOTIONS_PHOTO' =>'128*128'                      //動態縮圖大小
    ),

2、詳細程式碼
/**
     * 檔案上傳方法,TP在此處有個坑,當圖片名稱命名不規範時,圖片不能儲存而且不會提示錯誤
     * 成功返回圖片儲存路徑
     * 失敗返回相關失敗資訊
     */
    public function upload(){
        /**
         * file_put_contents('1.txt',var_export($_POST,true));
         * file_put_contents('2.txt',var_export($GLOBALS['HTTP_RAW_POST_DATA'],true));
         * $raw_post_data = file_get_contents('php://input', 'r');
         * file_put_contents('3.txt',var_export($raw_post_data, true));
         * file_put_contents('4.txt',var_export($_FILES, true));
         */
        $user_id = I('post.user_id',0,'intval');
        $type = I('get.type',1,'intval');//操作型別,1:使用者頭像上傳,2:圖片上傳,3:說說圖片上傳
        $token = $this->token;
        $data = array();
        if($user_id){
            //user_id有傳的話,那麼說明是更新使用者頭像操作
            $return = $this->check_user_valid($token,$user_id);
            if(!$return){
                $data['ret_code'] = C('API_STATUS_CODE.USER_DOES_NOT_HAVE_POWER');
                $data['ret_msg'] = C('API_STATUS_CODE.USER_DOES_NOT_HAVE_POWER_MSG');
                $this->ajaxReturn($data);
            }
        }
        //設定檔案存放路徑及縮放比例
        $folder = '';
        $thumb_size = '';
        switch($type){
            case 1:
                $folder = 'header';
                $thumb_size = C('IMAGES_THUMB_SIZE_SETTING.USER_HEADER');
                break;
            case 2:
                $folder = 'photos';
                $thumb_size = C('IMAGES_THUMB_SIZE_SETTING.PHOTOS_HEADER');
                break;
            case 3:
                $folder = 'emotions';
                $thumb_size = C('IMAGES_THUMB_SIZE_SETTING.EMOTIONS_PHOTO');
                break;
        }
        $path = C('SYSTEM_IMAGES_FOLDERS').'images/'.$folder;
        if(!file_exists($path)){
            mkdir($path);
            chmod($path,755);
        }

        $file_arr = explode('.',$_FILES['file']['name']);
        $file_name = $file_arr[0];
        $sha1 = sha1(time().mt_rand());

        $config = array();
        $config['maxSize'] = 3145728;
        $config['exts'] = array('jpg', 'gif', 'png', 'jpeg','JPG','GIF','PNG','JPEG');
        $config['rootPath'] = $path;
        $config['savePath'] = '/';
        $config['saveName'] = $sha1.'-'.$file_name;
        $upload  = new \Think\Upload($config);
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {
            $data['ret_code'] = C('API_STATUS_CODE.FAILED');
            $data['ret_msg'] = $upload->getError();
        }else{
            //檔案存放路徑
            $url = $path.$info['savepath'].$info['savename'];
            //生成縮圖
            $all_img_url = $this->_multi_thumb_save($path,$info,$sha1,$thumb_size,$_FILES['file']['name']);
            $data['ret_code'] = C('API_STATUS_CODE.SUCCESS');
            $data['ret_msg'] = C('API_STATUS_CODE.SUCCESS_MSG');
            $data['data'] = array(
                'url'           =>$url,
                'thumb_url'    =>$all_img_url
            );
        }
        $this->ajaxReturn($data);
    }

    /**
     * 批量生成不同尺寸縮圖
     * @param $path                原始圖片
     * @param $info                圖片上傳後獲得的object
     * @param $sha1                sha1()後得到的值
     * @param $size_arr            縮略尺寸陣列
     * @param $file_name           原始圖片名稱
     * @return string              所有縮圖地址字串
     */
    private function _multi_thumb_save($path,$info,$sha1,$size_arr,$file_name){
        $all_img_url = '';
        $img_url_arr = array();
        //需要生成多個縮圖
        if(is_array($size_arr)){
            foreach($size_arr as $key =>$value){
                $img_url_arr[$key] = $this->_thumb_save($path,$info,$sha1,$value,$file_name);
            }
            $all_img_url = json_encode($img_url_arr);
        }else{
            $all_img_url = $this->_thumb_save($path,$info,$sha1,$size_arr,$file_name);
        }
        return $all_img_url;
    }

    /**
     * 批量生成不同尺寸縮圖
     * @param $path                原始圖片
     * @param $info                圖片上傳後獲得的object
     * @param $sha1                sha1()後得到的值
     * @param $thumb_size          縮略尺寸
     * @param $file_name           原始圖片名稱
     * @return string              所有縮圖地址字串
     */
    private function _thumb_save($path,$info,$sha1,$thumb_size,$file_name){
        $source = $path.$info['savepath'].$info['savename'];
        $image = new \Think\Image();
        $image->open($source);
        $size = explode('*',$thumb_size);
        $width = $size[0];
        $height = $size[1];
        //如果原始圖片尺寸本來就小於縮略尺寸,那麼不做壓縮操作
        if($image->width() <= $width && $image->height() <= $height){
            $name = $source;
        }else{
            $name = $path.$info['savepath'].$sha1.'-'.$width.'x'.$height.'-'.$file_name;
            $image->thumb($width, $height,\Think\Image::IMAGE_THUMB_SCALE);
            $image->save($name);
        }
        return $name;
    }