ThinkPHP3.2.3 上传图片同时生成多张缩略图

浏览:5417 发布日期:2017/01/23 分类:功能实现
ThinkPHP3.2.3 上传图片同时生成多张缩略图
/**
     * 图像上传处理
     * @param [String] $path     [保存文件夹名称]
     * @param [String] $width     [缩略图宽度]
     * @param [String] $height     [缩略图高度]
     * @return [Array] [图片上传信息]
     */
    private function _upload($path, $width, $height) {
        // 文件上传
        $config = array(
            'maxSize'    => C('UPLOAD_MAX_SIZE'),            // 设置附件上传大小
            'exts'        => C('UPLOAD_EXTS'),                // 设置附件上传类型    
            'rootPath'    => C('UPLOAD_PATH') . $path . '/',     // 设置附件上传目录
            'replace'    => true,                    // 覆盖同名文件
            'saveName'    => array('uniqid',''),        // 文件名创建规则
            'autoSub'    => true,                    // 自动使用子目录保存上传文件
            'subName'    => array('date','Ymd'),        // 子目录创建规则
        );
        $upload = new \Think\Upload($config);        // 实例化上传类
        $info = $upload->upload();

        if (!$info) {
            return array('status' => 0, 'msg' => $upload->getError());
        } else {
            // 生成缩略图
            foreach ($info as $file) {
                // 获取原图地址
                $img = $config['rootPath'] . $file['savepath'] . $file['savename'];
                $image = new \Think\Image();            // GD库
                $image->open($img);                     // 打开原图
                $thumbWidth  = explode(',', $width);    // 获取宽度
                $thumbHeight = explode(',', $height);    // 获取高度
                // 设置缩略图宽、高、前缀
                $thumb = array(
                    1 => array('w' => $thumbWidth[0], 'h' => $thumbHeight[0], 'n' => 'max_'),
                    2 => array('w' => $thumbWidth[1], 'h' => $thumbHeight[1], 'n' => 'medium_'),
                    3 => array('w' => $thumbWidth[2], 'h' => $thumbHeight[2], 'n' => 'mini_'),
                );
                foreach ($thumb as $value){
                    // 生成缩略图保存路径,并命名
                    $save_path = $config['rootPath'] . $file['savepath'] . $value['n'] . $file['savename'];
                    // 设置宽高和缩略类型,并保存缩略图
                    $image->thumb($value['w'], $value['h'], \Think\Image::IMAGE_THUMB_CENTER)->save($save_path);
                }
                unlink($img);        //上传生成缩略图以后删除源文件
                return array(
                    'status' => 1,
                    'savepath' => array(
                        'max'     => $file['savepath'] . 'max_'.  $file['savename'],
                        'medium'=> $file['savepath'] . 'medium_' . $file['savename'],
                        'mini'    => $file['savepath'] . 'mini_' . $file['savename'],
                    ),
                );
            }
        }
    }
评论( 相关
后面还有条评论,点击查看>>