1、加入引用:
namespace App\Api\Controllers\V1;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Models\Customer;
use Image;
use Input;
2、代码实例:
/**
* 更新头像
* @desc 用户在个人中心更新图像
* @param uid int Y N 用户id
* @param head_image file Y N 上传文件name值,类似表单提交的时候name和value
* @return data.head_image object 修改头像后的大图像
* @return data.small_head_image object 修改头像后的小图像
*/
public function changeHeadImage(Request $request){
$input = $request->only('uid', 'head_image');
$empty_array_keys = array_keys(array_map('trim', $input), '');
if ($empty_array_keys) {
//有空数据项,则报错提示哪些字段不可以为空
return $this->responseError(join(',', $empty_array_keys) . ' can not be empty');
}
$user = $this->check_user($input['uid']);
//获取前缀路径
$sub_path=config('bcc.path_head_image_save');
//制作名称
$new_img_medium_name=date('YmdH_i_s') . '_medium_' . uniqid() . '.jpg';
$new_img_small_name=date('YmdH_i_s') . '_small_' . uniqid() . '.jpg';
//制作路径
$new_img_medium_path=$sub_path.$new_img_medium_name;
$new_img_small_path=$sub_path.$new_img_small_name;
//接收文件裁剪并保存
$bool_medium=Image::make(Input::file('head_image'))->resize(120, 120)->save($new_img_medium_path);
$bool_small=Image::make(Input::file('head_image'))->resize(60, 60)->save($new_img_small_path);
$customer = Customer::findOrFail($input['uid']);
//更新客户图像数据
$customer = Customer::where('id',$input['uid'])
->update(
['head_image' => $new_img_medium_name, 'small_head_image' => $new_img_small_name]
);
//如果成功,返回用户新的大小图像,如果失败,提示更新出错
if ($customer) {
return $this->responseSuccess(
[
'head_image'=>'http://' . $_SERVER['SERVER_NAME'].'/'.$new_img_medium_path,
'small_head_image'=>'http://' . $_SERVER['SERVER_NAME'].'/'.$new_img_small_path
]
);
}
return $this->responseError('changeHeadImage failed !');
}
返回结果:
{
"message": "Successfully",
"status_code": 200,
"data": {
"head_image": "http://xxx.com/public/avatars/2017073115_54_23_medium_597ee22fd5973.jpg",
"small_head_image": "http://xxx.com/public/avatars/2017073115_54_23_small_597ee22fd5984.jpg"
}
}