How to Resize Image before Upload in Laravel 11

Websolutionstuff | May-13-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to resize images before uploading in laravel 11. Here, we'll use the intervention/image composer package in laravel 11. Intervention Image is the most popular open source PHP image processing library.

It provides an easy and expressive way to edit images and supports PHP's two most common image processing libraries GD Library and Imagick.

Laravel 11 Resize Image Before Upload and Store in Database

Laravel 11 Resize Image Before Upload

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following composer command.

composer create-project laravel/laravel example-app

 

Step 2: Install Intervention Image Package

Then, we'll install the intervention/image composer package using the following command.

Before you begin with the installation make sure that your server environment supports the following requirements.

  • PHP >= 8.1
  • Mbstring PHP Extension
  • Image Processing PHP Extension
$ composer require intervention/image

 

Step 3: Define Routes

Next, we'll define routes into the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

 

Step 4: Create Controller File

Then, we'll create a new ImageController for image upload and resizing using the following command.

php artisan make:controller ImageController

Create images and thumbnails (inside the images folder) folder in the public folder.

app/Http/Controllers/ImageController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Intervention\Image\Laravel\Facades\Image;
  
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('image-upload');
    }
        
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);
   
        $image = $request->file('image');
        $imageName = time().'.'.$image->extension();
       
        $destinationPathThumbnail = public_path('images/thumbnail');
        $img = Image::read($image->path());
        $img->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPathThumbnail.'/'.$imageName);
     
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $imageName);
     
        return back()->with('success', 'Image Uploaded successfully!')
                     ->with('imageName', $imageName);
    }
}

 

Step 5: Create Blade File

Next, we'll create a blade file image-upload.blade.php to create a thumbnail.

resources/views/image-upload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Resize Image before Upload in Laravel 11 - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
        
<body>
<div class="container">
  
    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> How to Resize Image before Upload in Laravel 11 - Techsolutionstuff</h3>
        <div class="card-body">

            @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
  
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </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="/images/thumbnail/{{ Session::get('imageName') }}" />
                    </div>
                </div>
            @endsession
            
            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputImage">Image:</label>
                    <input 
                        type="file" 
                        name="image" 
                        id="inputImage"
                        class="form-control @error('image') is-invalid @enderror">
        
                    @error('image')
                        <span class="text-danger">{{ $message }}</span>
                    @enderror
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
                </div>
             
            </form>
        </div>
    </div>
</div>
</body>
</html>

 

Step 6: Run the Laravel  11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How to Generate Fake Data using Tinker in Laravel 11
How to Generate Fake Data usin...

Hello, laravel web developers! In this article, we'll see how to generate fake data using Tinker in laravel 11....

Read More

May-22-2024

Laravel 9 Generate PDF File Using DomPDF
Laravel 9 Generate PDF File Us...

In this tutorial, we will see laravel 9 generate pdf file using dompdf. For generating pdf files we will use the la...

Read More

Feb-25-2022

Laravel 9 One To One Relationship Example
Laravel 9 One To One Relations...

  In this article, we will see laravel 9 one to one relationship example. Also, you can use one to one re...

Read More

Apr-01-2022

How to Add Bootstrap 5 in Angular 17 Application
How to Add Bootstrap 5 in Angu...

Welcome to this tutorial where I'll guide you through the process of integrating Bootstrap 5 into your Angular 17 ap...

Read More

Mar-25-2024