How To Use Image Intervention In Laravel 9

    In this article, we will see how to use image intervention in laravel 9. Here, we will learn about image intervention and image resizing in laravel 8 and laravel 9. Also, we are using an intervention package for resizing images in laravel 9. So, let's see how to use intervention images in laravel 9.

    Intervention Image is an open source PHP image handling and manipulation library. It provides an easier and more expressive way to create, edit, and compose images and supports currently the two most common image processing libraries GD Library and Imagick.

    So, let's see the laravel 9 image intervention, install intervention image laravel 9, image resize in laravel 8 and laravel 9, and laravel resize image example.

    Step 1: Install Laravel 9

    Step 2: Install intervention/image Package

    Step 3: Create Route

    Step 4: Create Controller

    Step 5: Create Blade File

    Step 6: Run Laravel 9 Application

Step 1: Install Laravel 9

    In this step, we will install the laravel 9 application using the following command.

composer create-project laravel/laravel laravel9_image_intervention
Step 2: Install intervention/image Package

    Now, we will install the intervention/image package using the following composer command.

composer require intervention/image

    After you have installed Intervention Image, open your Laravel config file config/app.php and add the following lines.

    In the $providers array add the service providers for this package.

Intervention\Image\ImageServiceProvider::class

    Add the facade of this package to the $aliases array.

'Image' => Intervention\Image\Facades\Image::class

    Publish Configuration in Laravel

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"
Read Also: How To Image Optimization In Laravel 9 Using Spatie
Step 3: Create Route

    In this step, we will add routes to the web.php file. So, add the following code to that file.

    routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::controller(ImageController::class)->group(function(){
    Route::get('image-upload', 'index');
    Route::post('image-upload', 'store')->name('image.store');
});
Step 4: Create Controller

    Now, we will create an ImageController file. So, run the following command and create a controller.

php artisan make:controller ImageController

    app/Http/Controllers/ImageController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Image;
    
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('image_upload');
    }
        
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,svg|max:2048',
        ]);
      
        if($request->hasFile('image')) {
            $image = Image::make($request->file('image'));
            $imageName = time().'-'.$request->file('image')->getClientOriginalName();
            $destinationPath = public_path('images/');
            $image->save($destinationPath.$imageName);
            $destinationPathThumbnail = public_path('images/thumbnail/');
            $image->resize(100,100);
            $image->save($destinationPathThumbnail.$imageName);
  
            /**
             * Write Code for Image Upload Here,
             *
             * $upload = new Images();
             * $upload->file = $imageName;
             * $upload->save();            
            */
  
            return back()
                ->with('success','Image Upload successful')
                ->with('imageName',$imageName);
        }
       
        return back();
    }
}

    Note: create two folders one is "images" in the public folder and another "thumbnail" inside the images folder.

    Examples:

// create instance
$img = Image::make('public/foo.jpg');

// resize image to fixed size
$img->resize(300, 200);

// resize only the width of the image
$img->resize(300, null);

// resize only the height of the image
$img->resize(null, 200);

// resize the image to a width of 300 and constrain aspect ratio (auto height)
$img->resize(300, null, function ($constraint) {
    $constraint->aspectRatio();
});

// resize the image to a height of 200 and constrain aspect ratio (auto width)
$img->resize(null, 200, function ($constraint) {
    $constraint->aspectRatio();
});

// prevent possible upsizing
$img->resize(null, 400, function ($constraint) {
    $constraint->aspectRatio();
    $constraint->upsize();
});

// resize the image so that the largest side fits within the limit; the smaller
// side will be scaled to maintain the original aspect ratio
$img->resize(400, 400, function ($constraint) {
    $constraint->aspectRatio();
    $constraint->upsize();
});
Read Also: How To Image Upload Using Ajax In Laravel 9
Step 5: Create Blade File

    In this step, we will create an image_upload.blade.php file. So, add the following code to that file.

    resources/views/image_upload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How To Use Image Intervention In Laravel 9 - Websolutionstuff</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    
<div class="container">
    <h1>How To Use Image Intervention In Laravel 9 - Websolutionstuff</h1>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
           
    @if ($message = Session::get('success'))
      
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <strong>{{ $message }}</strong>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  
    <div class="row">
        <div class="col-md-4">
            <strong>Original Image:</strong>
            <br/>
            <img src="/images/{{ Session::get('imageName') }}" width="300px" />
        </div>
        <div class="col-md-4">
            <strong>Thumbnail Image:</strong>
            <br/>
            <img src="/thumbnail/{{ Session::get('imageName') }}" />
        </div>
    </div>
    @endif
            
    <form action="{{ route('image.store') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="row">
            <div class="col-md-12">
                <br/>
                <input type="file" name="image" class="image">
            </div>
            <div class="col-md-12">
                <br/>
                <button type="submit" class="btn btn-success">Upload Image</button>
            </div>
        </div>
    </form>
</div>
    
</body>
</html>
Step 6: Run Laravel 9 Application

    Now, we will run the laravel 9 image intervention using the following command.

php artisan serve

    Output:

    how_to_use_image_intervention_in_laravel_9_example

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan