Beispiel #1
0
 function crop($w, $h, $x, $y, $url)
 {
     $rootPath = C('FACE_PATH');
     //图片地址
     $bigFacePath = $rootPath . session('auth')['id'] . '_200*200.jpg';
     $smallFacePath = $rootPath . session('auth')['id'] . '_50*50.jpg';
     //裁剪图片
     $imgHandler = new Image();
     $imgHandler->open($url);
     $imgHandler->crop($w, $h, $x, $y);
     //保存大图
     $imgHandler->thumb(200, 200)->save($bigFacePath);
     //保存小图
     $imgHandler->thumb(50, 50)->save($smallFacePath);
     $pathArr = array(small => $smallFacePath, big => $bigFacePath);
     return $pathArr;
 }
 public function upload()
 {
     $token = I('post.token');
     $timestamp = I('post.timestamp');
     $verifyToken = md5('unique_salt' . $timestamp);
     if (!empty($_FILES) && $token == $verifyToken) {
         //上传参数配置
         $config = array('maxSize' => 3145728, 'rootPath' => './Uploads/', 'savePath' => '', 'saveName' => array('uniqid', ''), 'exts' => array('jpg', 'gif', '', 'jpeg'), 'autoSub' => true, 'subName' => array('date', 'Ymd'));
         $upload = new Upload($config);
         // 实例化上传类
         // 上传文件
         $info = $upload->upload();
         if (!$info) {
             // 上传错误提示错误信息
             $data = array('status' => 0, 'info' => $upload->getError());
         } else {
             // 上传成功
             //添加水印和缩略图
             $img_url = $config['rootPath'] . $info['Filedata']['savepath'] . $info['Filedata']['savename'];
             //图片地址
             $img = new Image(1, $img_url);
             $mark = "./Public/images/uploadify/hbh.png";
             //水印图片地址
             $img->water($mark);
             //添加水印默认是右下角
             $img->save($img_url);
             //保存水印后的图片
             $img->thumb(250, 150);
             //缩略图宽250px 高150px 等比例缩放
             $thumb_url = $config['rootPath'] . $info['Filedata']['savepath'] . 'tb_' . $info['Filedata']['savename'];
             //缩略图地址
             $img->save($thumb_url);
             //保存缩略图
             $data = array('savename' => $info['Filedata']['savename'], 'savepath' => $config['rootPath'] . $info['Filedata']['savepath'], 'status' => 1);
         }
         $this->ajaxReturn($data);
     }
 }
 /**
  * 上传图片
  * @param int $size 宽度
  */
 public function upload($size = 200)
 {
     $upload = new Upload();
     // 实例化上传类
     $upload->maxSize = 1024 * 1024 * 2;
     // 设置附件上传大小
     $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
     // 设置附件上传类型
     $upload->rootPath = __DIR__ . '/../../../upload/';
     // 设置附件上传根目录
     $upload->savePath = '';
     // 设置附件上传(子)目录
     // 上传文件
     $info = $upload->upload();
     if (!$info) {
         $this->ajaxReturn(array('error' => $upload->getError()));
     } else {
         $path = $upload->rootPath . $info['file']['savepath'] . $info['file']['savename'];
         $image = new Image();
         $image->open($path);
         $image->thumb($size, $size, Image::IMAGE_THUMB_CENTER)->save($path);
         $this->ajaxReturn(array('url' => U('/', '', false, true) . 'upload/' . $info['file']['savepath'] . $info['file']['savename']));
     }
 }
Beispiel #4
0
 /**
  * 头像更新
  * @author JunhaoHo
  */
 private function _updateAvatar()
 {
     $hasimg = $_FILES['pic']['name'] ? 1 : 0;
     if ($hasimg) {
         $upload = new Upload();
         $upload->maxSize = 1024 * 1024 * 2;
         // 设置附件上传大小
         $upload->exts = array('jpg', 'png', 'jpeg');
         // 设置附件上传类型
         $upload->saveName = array('uniqid', '');
         $upload->rootPath = C("UPLOAD_ROOT_PATH");
         // 设置附件上传根目录
         $upload->savePath = 'upload/avatar/';
         // 设置附件上传(子)目录
         $upload->autoSub = false;
         $upload->driver = 'Sae';
         // 上传文件
         $info = $upload->upload();
         if (!$info) {
             // 上传错误提示错误信息
             $result['code'] = self::UPDATE_AVATAR_FAILED_CODE;
             $error = $upload->getError();
             if (strpos($error, 'upload_max_filesize') || strpos($error, '文件大小不符')) {
                 $error = '头像大小不得大于2MB';
             } elseif (strpos($error, '后缀')) {
                 $error = '不支持该图片格式';
             }
             $result['error'] = $error;
         } else {
             // 上传成功
             $imgname = $info['pic']['savename'];
             //生成等比例缩略图
             $image = new Image();
             $path = $upload->rootPath . $upload->savePath;
             $image->open($path . $imgname);
             $image->thumb(128, 128)->save($path . 'thumbmini_' . $imgname, null, 90);
             $rs = D('Member')->updateMemberByUid(session('uid'), array('avatar' => $imgname));
             if ($rs) {
                 $result['code'] = self::UPDATE_AVATAR_SUCCESS_CODE;
                 session('avatar', $imgname);
             } else {
                 $result['code'] = self::UPDATE_AVATAR_FAILED_CODE;
                 $error = D('Member')->getDbError();
                 $error = substr($error, 0, strpos($error, "[ SQL语句 ]"));
                 $result['error'] = $error;
             }
         }
     }
     if ($result['code'] == self::UPDATE_AVATAR_FAILED_CODE) {
         $this->ajaxReturn($result);
     }
 }
Beispiel #5
0
 /**
  * 上传一个文件
  * @access protected
  * @param mixed $name 数据
  * @param string $value  数据表名
  * @return string
  */
 protected function save($file)
 {
     $filename = $file['save_path'] . $file['savename'];
     if (!$this->upload_replace && is_file($filename)) {
         // 不覆盖同名文件
         $this->error = '文件已经存在!' . $filename;
         return false;
     }
     // 如果是图像文件 检测文件格式
     if (in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
         $info = getimagesize($file['tmp_name']);
         if (false === $info || 'gif' == strtolower($file['extension']) && empty($info['bits'])) {
             $this->error = '非法图像文件';
             return false;
         }
     }
     if (!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename, 'utf-8', 'gbk'))) {
         $this->error = '文件上传保存错误!';
         return false;
     }
     if ($this->thumb && in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png'])) {
         $image = getimagesize($filename);
         if (false !== $image) {
             //是图像文件生成缩略图
             $thumbWidth = explode(',', $this->thumb_max_width);
             $thumbHeight = explode(',', $this->thumb_max_height);
             $thumb_prefix = explode(',', $this->thumb_prefix);
             $thumb_suffix = explode(',', $this->thumb_suffix);
             $thumb_file = explode(',', $this->thumb_file);
             $thumb_path = $this->thumb_path ? $this->thumb_path : dirname($filename) . '/';
             $thumb_ext = $this->thumb_ext ? $this->thumb_ext : $file['extension'];
             //自定义缩略图扩展名
             // 生成图像缩略图
             for ($i = 0, $len = count($thumbWidth); $i < $len; $i++) {
                 if (!empty($thumb_file[$i])) {
                     $thumbname = $thumb_file[$i];
                 } else {
                     $prefix = isset($thumb_prefix[$i]) ? $thumb_prefix[$i] : $thumb_prefix[0];
                     $suffix = isset($thumb_suffix[$i]) ? $thumb_suffix[$i] : $thumb_suffix[0];
                     $thumbname = $prefix . basename($filename, '.' . $file['extension']) . $suffix;
                 }
                 Image::thumb($filename, $thumb_path . $thumbname . '.' . $thumb_ext, '', $thumbWidth[$i], $thumbHeight[$i], true);
             }
             if ($this->thumb_remove_origin) {
                 // 生成缩略图之后删除原图
                 unlink($filename);
             }
         }
     }
     if ($this->zipImags) {
         // TODO 对图片压缩包在线解压
     }
     return true;
 }
 public function img()
 {
     //实例化图像处理类,默认为GD库
     $image = new Image();
     //加载一张预处理的图片
     $image->open('./Public/images/1.jpg');
     //上面两句,可以用一句话包含
     //$image = new Image(Image::IMAGE_GD, './Public/images/1.jpg');
     //获取图片信息
     $arr['width'] = $image->width();
     $arr['height'] = $image->height();
     $arr['type'] = $image->type();
     $arr['mime'] = $image->mime();
     $arr['size'] = $image->size();
     //裁剪图片,高400,宽400
     $image->crop(400, 400)->save('./Public/images/1.jpg');
     $image->open('./Public/images/2.jpg');
     $image->thumb(300, 300, Image::IMAGE_THUMB_CENTER)->save('./Public/images/2.jpg');
     //在图片右下角添加水印并生成
     $image->open('./Public/images/3.jpg');
     $image->water('./Public/images/logo.png')->save('./Public/images/3.jpg');
     echo '<pre>' . print_r($arr, 1) . '</pre>';
 }
Beispiel #7
0
function cropImg($filepath, $webpath)
{
    $image = new \Think\Image();
    $filepath = legalize_path($filepath);
    var_dump($filepath);
    $image->open($filepath);
    $savepath = $filepath;
    $x = I("post.x1", 0, 'intval');
    $y = I("post.y1", 0, 'intval');
    $w = I("post.w", 0, 'intval');
    $h = I("post.h", 0, 'intval');
    if ($w > 0 && $h > 0) {
        $image->crop($w, $h, $x, $y, $w, $h)->save($savepath);
    }
    echo "<img src='{$webpath}' />";
    $savepath = $webpath;
    //dump($webpath);
    //dump($thumb_savepath);
    return $savepath;
}
 /**
  * 上传头像图片
  * @author huajie <*****@*****.**>
  */
 public function uploadPhoto()
 {
     //TODO: 用户登录检测
     /* 返回标准数据 */
     $return = array('status' => 1, 'info' => '上传成功', 'data' => '');
     /* 调用文件上传组件上传文件 */
     $Picture = D('Picture');
     $pic_driver = C('PHOTO_UPLOAD_DRIVER');
     $info = $Picture->upload($_FILES, C('PHOTO_UPLOAD'), C('PHOTO_UPLOAD_DRIVER'), C("UPLOAD_{$pic_driver}_CONFIG"));
     //TODO:上传到远程服务器
     /* 记录图片信息 */
     if ($info) {
         $return['status'] = 1;
         $return = array_merge($info['download'], $return);
         $image = new Image();
         $path = strpos($return['path'], '/') == 0 ? substr($return['path'], 1) : $return['path'];
         $image->open($path);
         if ($image->width() > 500 || $image->width > 300) {
             $image->thumb(500, 300);
             $image->save($path, null, 100, true);
         }
     } else {
         $return['status'] = 0;
         $return['info'] = $Picture->getError();
     }
     /* 返回JSON数据 */
     echo json_encode($return);
     //$this->ajaxReturn($return);
 }
 public function water()
 {
     $path = './Public/images/demo.jpg';
     $water = './Public/images/logo.png';
     $image = new Image(Image::IMAGE_GD, $path);
     $image->water($water)->save('./Public/images/demo-water.jpg');
 }
 public function test()
 {
     $image = new Image();
     $info['path'] = '/';
     if (!file_exists('.' . $info['path'])) {
         return false;
     }
     $image->open(realpath('.' . $info['path']));
     $thumbnail_path = C('THUMBNAIL_PATH') . '/' . date('Y-m-d', time()) . '/';
     if (!is_dir($thumbnail_path)) {
         if (!mkdir($thumbnail_path)) {
             return false;
         }
     }
 }
Beispiel #11
0
 /**
  * 上传分类图片
  * @author liuxiaolin
  * @access public
  * @return
  */
 public function picUpload()
 {
     $picArr['dataID'] = intval($_POST['dataID']);
     $upload = new \Think\Upload(C('PIC_UPLOAD'));
     $file_name = $_FILES['file']['name'];
     $ext = pathinfo($file_name, PATHINFO_EXTENSION);
     if ($ext == 'gif') {
         $res = ['code' => 0, 'info' => '不能上传gif'];
         $this->ajaxReturn($res);
     }
     $upload->savePath = 'Class/';
     $images = $upload->upload();
     //开始上传
     if ($images) {
         $picArr['picUrl'] = C('PIC_UPLOAD.rootPath') . $images['file']['savepath'] . $images['file']['savename'];
         $thumUrl = str_replace('.' . $images['file']['ext'], '_thumb.' . $images['file']['ext'], $picArr['picUrl']);
         //生成110*110的缩略图
         $img = new Image();
         $img->open($picArr['picUrl'])->thumb('300', '200', Image::IMAGE_THUMB_CENTER)->save($thumUrl);
         //返回文件地址和名给JS作回调用
         $res = ['code' => 1, 'info' => $picArr];
         $this->ajaxReturn($res, 'json');
     } else {
         //上传失败,返回错误
         $res = ['code' => 0, 'info' => $upload->getError()];
         $this->ajaxReturn($res, 'json');
     }
 }
Beispiel #12
0
 /**
  * 添加
  */
 public function postUpload()
 {
     $upload = new \Think\Upload();
     $upload->savePath = 'Sq/';
     //设置附件上传目录
     //上传图片
     $info = $upload->upload();
     $picUrl = C('PIC_UPLOAD.rootPath') . $info['file']['savepath'] . $info['file']['savename'];
     if ($info) {
         $thumUrl = str_replace('.' . $info['file']['ext'], '_thumb.' . $info['file']['ext'], $picUrl);
         //生成300*200的缩略图
         $img = new Image();
         $img->open($picUrl)->thumb('300', '200', Image::IMAGE_THUMB_CENTER)->save($thumUrl);
         $this->ajaxReturn($picUrl, 'json');
     } else {
         exit("0," . $upload->getError());
     }
 }
Beispiel #13
0
 /**
  * 发表回复
  * @author JunhaoHo
  */
 public function addPost()
 {
     $aid = I('aid', null);
     $content = I('content', '');
     if (empty($aid)) {
         $result['code'] = self::BAD_REQUEST_CODE;
         $result['error'] = "非法请求:请求参数不完整";
     } else {
         $uid = session('uid');
         $username = session('username');
         $dateline = time();
         $hasimg = $_FILES['pic']['name'] ? 1 : 0;
         if ($hasimg) {
             $upload = new Upload();
             $upload->maxSize = 1024 * 1024 * 3;
             // 设置附件上传大小
             $upload->exts = array('jpg', 'png', 'jpeg');
             // 设置附件上传类型
             $upload->saveName = array('uniqid', '');
             $upload->rootPath = C("UPLOAD_ROOT_PATH");
             // 设置附件上传根目录
             $upload->savePath = 'upload/post/image/';
             // 设置附件上传(子)目录
             $upload->autoSub = false;
             $upload->driver = 'Sae';
             // 上传文件
             $info = $upload->upload();
             if (!$info) {
                 // 上传错误提示错误信息
                 $result['code'] = self::UPLOAD_IMG_FAILED_CODE;
                 $error = $upload->getError();
                 if (strpos($error, 'upload_max_filesize')) {
                     $error = '图片大小不得大于3MB';
                 } elseif (strpos($error, '后缀')) {
                     $error = '不支持该图片格式';
                 }
                 $result['error'] = $error;
                 $this->ajaxReturn($result);
             } else {
                 // 上传成功
                 $imgname = $info['pic']['savename'];
                 //生成等比例缩略图
                 $image = new Image();
                 $path = $upload->rootPath . $upload->savePath;
                 $image->open($path . $imgname);
                 $image->thumb(320, 320)->save($path . 'thumbsmall_' . $imgname, null, 90);
                 $image->open($path . $imgname);
                 $image->thumb(640, 640)->save($path . 'thumbmedium_' . $imgname, null, 90);
             }
         } else {
             if (empty($content)) {
                 //图文都无不能post
                 $result['code'] = self::BAD_REQUEST_CODE;
                 $result['error'] = "您无语了吗...";
                 $this->ajaxReturn($result);
             } else {
                 $imgname = '';
             }
         }
         $post = array('aid' => $aid, 'uid' => $uid, 'username' => $username, 'hasimg' => $hasimg, 'img' => $imgname, 'content' => $content, 'dateline' => $dateline);
         $rs = D('Post')->addPost($post);
         if ($rs) {
             $result['code'] = self::ADD_POST_SUCCESS_CODE;
             D('Activity')->updateActivityCounterByAid($aid, 'replies');
         } else {
             $result['code'] = self::ADD_POST_FAILED_CODE;
             $error = D('Post')->getDbError();
             $error = substr($error, 0, strpos($error, "[ SQL语句 ]"));
             $result['error'] = $error;
         }
     }
     $this->ajaxReturn($result);
 }
 public function img_upload()
 {
     //     	if(!session('userNmae')){
     //     		$this->error('登陆时间超时,请重新登陆',U('Home/Index/index'));
     //     		exit;
     //     	}
     $user = M('userinfo');
     $condition['userName'] = session('userName');
     $userID = $user->where($condition)->getField('userID');
     $imgpath = $user->where($condition)->getField('imagePath');
     $upload = new Upload();
     $upload->maxSize = 5 * 1024 * 1024;
     //上传头像不超过5M
     $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
     $upload->savePath = './images/';
     $upload->autoSub = false;
     $upload->saveName = 'img' . '_' . $userID . time();
     //命名方式,img+userid+当前时间戳
     $info = $upload->upload();
     if ($info) {
         $urlDir = 'Uploads/images/';
         if ($imgpath) {
             //如果存在已经有的头像,先删除
             if (file_exists($imgpath) && is_file($imgpath)) {
                 $fileName = basename($imgpath);
                 unlink($imgpath);
                 //删除用户头像
             }
             if (file_exists($urlDir . $fileName) && is_file($urlDir . $fileName)) {
                 unlink($urlDir . $fileName);
             }
         }
         foreach ($info as $file) {
             $saveName = $file['savename'];
             break;
         }
         if (!file_exists($urlDir . 'userImg')) {
             mkdir($urlDir . 'userImg');
         }
         if (file_exists($urlDir . $saveName)) {
             $image = new Image();
             $image->open($urlDir . $saveName);
             $image->thumb(99, 95, Image::IMAGE_THUMB_CENTER)->save($urlDir . 'userImg/' . $saveName);
             $user->where($condition)->setField('imagePath', $urlDir . 'userImg/' . $saveName);
             ///////////////////////////////////////////////////
             //跟新头像
             $leamessage = M('leamessage');
             $ansmessage = M('ansmessage');
             unset($condition);
             $condition['userID'] = session('userID');
             $leamessage->where($condition)->setField('imagePath', $urlDir . 'userImg/' . $saveName);
             $ansmessage->where($condition)->setField('imagePath', $urlDir . 'userImg/' . $saveName);
         }
         $result = array('status' => 1, 'msg' => $urlDir . 'userImg/' . $saveName);
         echo json_encode($result);
     } else {
         $result = array('status' => 0, 'msg' => $upload->getError());
         echo json_encode($result);
     }
 }
 /**
  * 生成缩略图
  * @param $info
  * @param $size
  * @return string
  */
 protected function generate($info, $size)
 {
     $thumbnail = M('Thumbnail');
     $result = $thumbnail->where(array('width' => $size, 'pic_id' => $info['id']))->find();
     if (!empty($result)) {
         return $result['url'];
     }
     $image = new Image();
     $image->open('.' . $info['path']);
     $thumbnail_path = C('THUMBNAIL_PATH') . '/' . date('Y-m-d', time()) . '/';
     if (!is_dir($thumbnail_path)) {
         mkdir($thumbnail_path);
     }
     $save_name = $info['savename'] . '.w' . $size;
     $image->thumb($size, $size, Image::IMAGE_THUMB_CENTER)->save($thumbnail_path . $save_name);
     $entity = array('pic_id' => $info['id'], 'path' => ltrim($thumbnail_path . $save_name, '.'), 'url' => $this->getSiteURL() . ltrim($thumbnail_path . $save_name, "."), 'width' => $size, 'create_time' => time());
     $thumbnail_url = "";
     if ($thumbnail->create($entity)) {
         $thumbnail_id = $thumbnail->add();
         if ($thumbnail_id === false) {
             LogRecord($thumbnail->getDbError(), __FILE__ . ',行:' . __LINE__);
         } else {
             $thumbnail_url = $thumbnail_path . $save_name;
         }
     }
     return $thumbnail_url;
 }
 /**
  *上传userInfo到数据库
  */
 public function userInfo()
 {
     $upload = new \Think\Upload();
     $upload->maxSize = 1000000;
     $upload->exts = array('jpg', 'png', 'jpeg');
     $upload->rootPath = './Public/Bzone/images/head-pic/';
     $upload->savePath = '';
     $upload->replace = 'true';
     $upload->saveName = 'time';
     $info = $upload->upload();
     if (!$info) {
         $this->error($upload->getError());
     } else {
         foreach ($info as $file) {
             $image = new Image();
             $image->open('./Public/Bzone/images/head-pic/' . $file['savepath'] . $file['savename']);
             $width = $image->width();
             $height = $image->height();
             if ($width <= 130 || $height <= 130) {
                 $image->crop(130, 130)->save('./Public/Bzone/images/head-pic/' . $file['savepath'] . $file['savename']);
             } else {
                 $image->thumb(130, 130)->save('./Public/Bzone/images/head-pic/' . $file['savepath'] . $file['savename']);
             }
             $data['info_pic'] = $file['savepath'] . $file['savename'];
             $data['info_selfintroduce'] = I('selfInfo');
             if (M('userinfo')->where(array('user_id' => session('userId')))->save($data)) {
                 redirect(U('Bzone/showFabu', '', ''));
             } else {
                 $this->error('上传失败');
             }
         }
     }
 }
 /**
  * 上传分类信息图片处理(多张).
  * 每次最多允许上传 10 张.
  * 
  * @access public
  * @return void
  */
 public function uploadImgAction()
 {
     if (empty($_FILES)) {
         $this->setAjaxData(Message::FAILED, '没有要上传的文件')->myAjaxReturn();
     }
     $allow_max_num = C('upload_img_max_num');
     $up_max_num = count($_FILES['classified']['name']);
     if ($up_max_num > $allow_max_num) {
         for ($i = $allow_max_num; $i < $up_max_num; ++$i) {
             unset($_FILES['classified']['name'][$i]);
             unset($_FILES['classified']['type'][$i]);
             unset($_FILES['classified']['tmp_name'][$i]);
             unset($_FILES['classified']['error'][$i]);
             unset($_FILES['classified']['size'][$i]);
         }
     }
     $this->uploadSavePath = 'Class/';
     $result = $this->imageUpload();
     if (!is_array($result)) {
         $this->setAjaxData(Message::FAILED, $result)->myAjaxReturn();
     }
     $classifiedImgPath = [];
     $rootPath = C('PIC_UPLOAD.rootPath');
     $image = new Image();
     $thumbImgConf = C('thumb_image');
     foreach ($result as $f) {
         // 生成缩略图.
         $oriPath = $rootPath . $f['savepath'] . $f['savename'];
         $thumbPath = str_replace('.' . $f['ext'], '_thumb.' . $f['ext'], $oriPath);
         $image->open($oriPath)->thumb($thumbImgConf['width'], $thumbImgConf['height'], Image::IMAGE_THUMB_CENTER)->save($thumbPath);
         $classifiedImgPath[] = $this->resolveImgUrlPath($thumbPath);
     }
     unset($result, $image);
     $this->setAjaxData(Message::SUCCESS, Message::get(Message::SUCCESS), ['classified' => $classifiedImgPath])->myAjaxReturn();
 }
Beispiel #18
0
 public function changePhoto()
 {
     if (IS_POST) {
         $id = is_login();
         $basepath = substr($_POST['basepath'], 1);
         $image = new Image();
         $image->open($basepath);
         $image->crop($_POST['w'], $_POST['h'], $_POST['x'], $_POST['y'], 200, 200);
         $last = strrpos($basepath, '/') + 1;
         $ext = substr($basepath, strrpos($basepath, '.'));
         $path = substr($basepath, 0, $last);
         $filename = $path . 'crop_' . $id . $ext;
         $image->save($filename, null, 100, false);
         $filename = '/' . $filename . '?t=' . NOW_TIME;
         $user = array('id' => is_login(), 'photo' => $_POST['photo'], 'photo_url' => $filename);
         M('Users')->save($user);
         memberupdate($id, $user['photo_url']);
         $ret = array('status' => 1, 'info' => '头像更改成功!', 'photo_url' => $filename, 'photo' => $_POST['photo']);
         $this->ajaxReturn($ret);
         $this->success('头像更改成功!');
     } else {
         $this->display('changePhoto');
     }
 }
 private function do_upload()
 {
     // Make sure file is not cached (as it happens for example on iOS devices)
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Cache-Control: post-check=0, pre-check=0", false);
     header("Pragma: no-cache");
     if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
         exit;
         // finish preflight CORS requests here
     }
     if (!empty($_REQUEST['debug'])) {
         $random = rand(0, intval($_REQUEST['debug']));
         if ($random === 0) {
             header("HTTP/1.0 500 Internal Server Error");
             exit;
         }
     }
     @set_time_limit(5 * 60);
     $uploadBaseDir = DOCUMENT_ROOT . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;
     $targetDir = $uploadBaseDir . 'tmp';
     $uploadDir = $uploadBaseDir . date('Y' . DIRECTORY_SEPARATOR . 'm');
     $cleanupTargetDir = true;
     // Remove old files
     $maxFileAge = 5 * 3600;
     // Temp file age in seconds
     // Create target dir
     if (!file_exists($targetDir)) {
         @mkdir($targetDir);
     }
     // Create target dir
     if (!file_exists($uploadDir)) {
         @mkdir($uploadDir, 0777, true);
     }
     // Get a file name
     //        if (isset($_REQUEST["name"])) {
     //            $fileName = $_REQUEST["name"];
     //        } elseif (!empty($_FILES)) {
     //            $fileName = $_FILES["file"]["name"];
     //        } else {
     //            $fileName = uniqid("file_");
     //        }
     $fileName = uniqid("pic_") . '.jpg';
     $md5File = @file($uploadBaseDir . 'md5list2.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
     $md5File = $md5File ? $md5File : array();
     if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File) !== FALSE) {
         die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1}');
     }
     $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
     $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
     // Chunking might be enabled
     $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
     $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
     // Remove old temp files
     if ($cleanupTargetDir) {
         if (!is_dir($targetDir) || !($dir = opendir($targetDir))) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
         }
         while (($file = readdir($dir)) !== false) {
             $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
             // If temp file is current file proceed to the next
             if ($tmpfilePath == "{$filePath}.part") {
                 continue;
             }
             // Remove temp file if it is older than the max age and is not the current file
             if (preg_match('/\\.part$/', $file) && filemtime($tmpfilePath) < time() - $maxFileAge) {
                 @unlink($tmpfilePath);
             }
         }
         closedir($dir);
     }
     // Open temp file
     if (!($out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb"))) {
         die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
     }
     if (!empty($_FILES)) {
         if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
         // Read binary input stream and append it to temp file
         if (!($in = @fopen($_FILES["file"]["tmp_name"], "rb"))) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
         }
     } else {
         if (!($in = @fopen("php://input", "rb"))) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
         }
     }
     while ($buff = fread($in, 4096)) {
         fwrite($out, $buff);
     }
     @fclose($out);
     @fclose($in);
     // Check if file has been uploaded
     if (!$chunks || $chunk == $chunks - 1) {
         // Strip the temp .part suffix off
         rename("{$filePath}.part", $filePath);
         rename($filePath, $uploadPath);
         array_push($md5File, $this->mymd5($uploadPath));
         $md5File = array_unique($md5File);
         file_put_contents($uploadBaseDir . 'md5list2.txt', join($md5File, "\n"));
     }
     // Return Success JSON-RPC response
     $img = new Image();
     $img->open($uploadPath);
     $img->thumb(800, 800);
     $img->save($uploadPath);
     $imgSize = $img->size();
     $file_path = strtr($uploadPath, array(DOCUMENT_ROOT => '', '\\' => '/'));
     $photoData = array('uid' => $this->uid, 'file_path' => $file_path, 'status' => 1, 'w' => $imgSize[0], 'h' => $imgSize[1]);
     $pid = D('Photo')->add($photoData);
     $this->responseSuccess(compact('pid') + $photoData);
 }