Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use Intervention Image to manipulate images in Livewire


Can I use Intervention Image to manipulate images in Livewire


Yes, you can use Intervention Image to manipulate images in Laravel Livewire components. Here's how you can integrate Intervention Image with Livewire for image uploads and manipulation:

1. Install the required packages:

bash
composer require intervention/image

2. In your Livewire component, use the `WithFileUploads` trait and define the image property:

php
use Livewire\Component;
use Livewire\WithFileUploads;
use Intervention\Image\Facades\Image;

class ImageUpload extends Component
{
    use WithFileUploads;

    public $image;

    public function save()
    {
        $this->validate([
            'image' => 'image|max:1024', // 1MB Max
        ]);

        $imagePath = $this->image->store('images', 'public');

        $img = Image::make(public_path("storage/{$imagePath}"))->fit(300, 300);
        $img->save();

        // Save the image path to the database or perform other actions
    }
}

3. In your Blade template, include the file input field and display the uploaded image preview:

html
<div>
    <form wire:submit.prevent="save">
        <input type="file" wire:model="image">

        @if ($image)
            <img src="{{ $image->temporaryUrl() }}" width="300">
        @endif

        @error('image')
            <span class="error">{{ $message }}</span>
        @enderror

        <button type="submit">Save Image</button>
    </form>
</div>

4. When the user selects an image, Livewire will automatically handle the upload process.

5. To manipulate the uploaded image using Intervention Image, you can use the `Image` facade:

php
$imagePath = $this->image->store('images', 'public');

$img = Image::make(public_path("storage/{$imagePath}"))->fit(300, 300);
$img->save();

This code will store the uploaded image in the `images` directory within your application's `storage/app/public` folder. It will then create a 300x300 pixel square thumbnail using the `fit()` method and save the modified image.

6. You can customize the image manipulation as per your requirements, such as resizing, cropping, or applying filters using Intervention Image's methods.

By following these steps, you can seamlessly integrate Intervention Image with your Laravel Livewire components for image uploads and manipulation, providing a smooth user experience for your application.

Citations:
[1] https://forum.laravel-livewire.com/t/laravel-livewire-intervention-images/2619
[2] https://gist.github.com/daugaard47/659984245d31b895d00ee5dcbdee44ec
[3] https://stackoverflow.com/questions/65134937/laravel-livewire-intervention-images
[4] https://www.youtube.com/watch?v=Xo1EfyQ3dc0
[5] https://www.youtube.com/watch?v=IHqRdNESbmQ