composer安装:
composer require intervention/image
laravel配置:1.编辑 config/app.php
$providers 添加 Intervention\Image\ImageServiceProvider::class
$aliases 添加 'Image' => Intervention\Image\Facades\Image::class
2.默认使用的是 'GD' 库,想修改的话,需要配置驱动,我们来生成配置文件:
php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"
生成 config/image.php 配置文件
demo实例:
1,表单
2,控制器
3,Api接口实现上传
namespace App\Http\Api;
use Illuminate\Http\Request;
use Exception;
use App\Http\Requests;
use Purifier;
use App\Http\Api\ApiController;
use DB;
use Intervention\Image\ImageManagerStatic as Image;//依赖包的Image静态方法生成缩略图
class UploadsServer
{
public static function uploads($code,$message='',$data)
{
if (!is_numeric($code)) {
return "";
}
try{
$file = $data['user_img']; //用户头像
if ($file) {
if ($file->isValid()) {
$path = "userlogo/";
if (!is_dir($path)) {
mkdir($path,0777,true);
}
$filename = date('YmdHis').uniqid().'.'.$file->getClientOriginalExtension();
$res = $file->move($path, $filename);
if ($res) {
$new_filename = $path.'/'.$filename;
$thumb_name = 'thumb_'.$filename;
$thumb = $path.'/'.$thumb_name;
Image::make($new_filename)->resize(50, 50)->save($thumb); //生成缩略图
$param = [
'user_img' => $thumb_name,
'user_idcard' => $data['user_idcard'],
'user_realname' => $data['user_realname'],
'user_id' => $data['user_id']
];
$bool = DB::table('user_message')->insert($param);
if ($bool) {
ApiController::json($code,$message);
} else {
throw new Exception('图片上传失败');
}
} else {
throw new Exception('图片上传失败');
}
}else{
throw new Exception('图片上传异常');
}
} else {
throw new Exception('请选择图片');
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
恭喜你成功啦!
参考网址:http://image.intervention.io/