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
Datatables Show And Hide Columns Dynamically In jQuery
Datatables Show And Hide Colum...

In this article, we will see how to hide and show columns in datatable in jquery. This example shows how you can ma...

Read More

Jun-07-2022

Next Previous Link Button Pagination in Laravel
Next Previous Link Button Pagi...

Today we will learn next previous link button pagination in laravel, Using paginate method you can easily create paginat...

Read More

Jun-14-2021

Github And Git Commands
Github And Git Commands

GitHub, Inc. is a United States-based global company that provides hosting for software development and version control...

Read More

Jul-15-2020

Laravel tips: DB Models and Eloquent - Part 2
Laravel tips: DB Models and El...

Laravel, the PHP web application framework, is renowned for its elegant and efficient approach to handling databases thr...

Read More

Oct-13-2023