Intervention Image is an open source PHP image handling and manipulation library. It provides an easy way to manipulate images. In addition, it integrates tightly with Laravel.
Installation
- Install package
> composer require intervention/image
- Integration with Laravel: becoming a Service Provider
Add the following lines into Laravel config file config/app.php
. it will be added into the $providers array, which is the service providers for this package.
config/app.php
'providers' => [
:
:
/*
* Package Service Providers...
*/
Intervention\Image\ImageServiceProvider::class,
],
- Add the facade of this package to the $aliases array.
config/app.php
'aliases' => [
:
:
'Image' => Intervention\Image\Facades\Image::class,
],
Now the Image Class will be auto-loaded by Laravel.
Usage
- View file:
app/resources/views/products/edit.blade.php
:
<form method="post" action="{{ route('products.update', $product->id) }}" enctype="multipart/form-data">
@method('PATCH')
@csrf
:
<!-- upload pictures -->
<div id="upload_pictures">
@foreach ($images as $image)
<div class="form-group">
<div class="col-md-10">
<input type="file" class="form-control-file" name="prod_img[]" id="prod_img[]">
</div>
</div>
@endforeach
</div>
<!-- upload pictures -->
<a class="btn btn-secondary" href="{{ URL::previous() }}">Back</a>
<button type="submit" class="btn btn-primary">Update</button>
</form>
- Controller:
app/Http/Controllers/ProductController.php
use Image;
:
:
public function update(Request $request, $id)
{
:
// Save upload files
$images = $request->file('prod_img');
foreach ($images as $key => $image) {
$img = Image::make($image);
$img->fit(600,600);
$img->save(public_path('/prod_imgs').'/'.$id.'_'.$key.'.png');
}
:
}