基于intervention对于上传图片的预处理

intervention 是一个php的图片处理库,之前有记录过(基于laravel-admin库)。这次用它来对客户上传的图片进行自动裁剪处理

Posted by 昆山吴彦祖 on 2019.12.27

1、安装

composer require intervention/image


2、使用

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;

use App\Customer;
use App\CustomerImage;
use Illuminate\Http\Request;
use Image;

class CustomerImageController extends Controller
{

public function add(Request $request){
	$request->validate([
		'image' => 'required|image|between:20,1024',
	]);
	//存圖片
	
        //对图片存储路径预处理
	$img = Image::make($request->file('image'));
	$dir = 'uploads/customer/'.session('customer_id');
	if(!is_dir($dir)){
		mkdir($dir);
	}
        //图片的真实存储路径
	$path = $dir.'/'.time().'.jpg';
        //图片数据库中存储路径
	$path_store = 'customer/'.session('customer_id').'/'.time().'.jpg';
	$img->fit(500,500)->save($path);
		
	//$path = Storage::disk('admin')->putFile('customer', $img);
	//圖片自動裁剪
	//$img = Image::make(config('app.url').'/uploads/'.$path);
		
	$customer = Customer::findOrFail(session('customer_id'));
		
	$customer_image = new CustomerImage;
        //如果当前用户没有图片 则第一张图设为封面
	$customer_image->is_cover = $customer->customerimage()->count()?2:1;
	$customer_image->image = $path_store;
	$customer_image->customer_id = session('customer_id');
	$customer_image->save();
		
	return redirect('/account/album');
	}
}


intervention-image