Image Resize in Laravel 10 : A comprehensive Guide

Introduction to image resize in Laravel:

In this tutorial, we’ll walk you through the process of creating a powerful image resizing functionality using the Laravel framework. With this step-by-step guide, you’ll learn how to set up a complete web application that allows users to upload images, automatically resize them, and view both the original and resized versions.

Prerequisites:

Before we begin, make sure you have the following:

  1. Basic understanding of PHP and Laravel.
  2. Composer installed on your system.
  3. Laravel installed globally.

Step 1: Creating the Laravel Project

Let’s start by creating a new Laravel project named “ImageResizer”:

composer create-project --prefer-dist laravel/laravel ImageResizer

Step 2: Installing Dependencies

For image manipulation, we’ll use the Intervention Image package. Install it by running:

composer require intervention/image

Step 3: Creating the Model and Database Table

Generate a model named “Image” and its corresponding migration to store image information:

php artisan make:model Image -m

In the migration file, add columns for image paths and sizes:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('image_path');
            $table->string('resized_image_path');
            $table->string('image_original_size')->nullable();
            $table->string('image_resized_size')->nullable();
            $table->timestamps();
        });
    }
    

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('images');
    }
};

Run the migration to create the table:

php artisan migrate

Step 4: Creating the Controller

Generate a controller named “ImageController” and set up routes for uploading, resizing, and viewing images:

php artisan make:controller ImageController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Image;
use Intervention\Image\Facades\Image as Resize;
use Illuminate\Support\Facades\File;

class ImageController extends Controller
{
    public function showUploadForm()
    {
       $data['images'] =  Image::all();
        return view('upload', $data);
    }

    public function uploadAndResize(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust the validation rules as needed
        ]);

        $imagePath = $request->file('image')->store('public');
        $imageName = basename($imagePath);
        // Resize the image
        $img = Resize::make(storage_path('app/' . $imagePath));
        $img->resize(300, 200);
        $resizedImagePath = 'resized_' . $imageName;
        $img->save(storage_path('app/public/images/' . $resizedImagePath));

        // Get image sizes
        $originalSize = File::size(storage_path('app/' . $imagePath));
        $resizedSize = File::size(storage_path('app/public/images/' . $resizedImagePath));
        // Store image information in the database
        $image = new Image();
        $image->image_path = $imageName;
        $image->resized_image_path = $resizedImagePath;
        $image->image_original_size = $originalSize;
        $image->image_resized_size = $resizedSize;
        $image->save();

        return redirect()->back()->with('success', 'Image uploaded and resized successfully.');
    }
    public function showImages($id)
    {
        $image = Image::findOrFail($id);
    
        $originalImagePath = asset('storage/' . $image->image_path);
        $resizedImagePath = asset('storage/images/'. $image->resized_image_path);
        return view('show', compact('originalImagePath', 'resizedImagePath'));
    }
    
}

In the controller, implement methods to handle image upload, resizing, and displaying images. Refer to previous responses for detailed code examples.

Step 5: Creating the Views

Create a Blade view file named “upload.blade.php” in the “resources/views” directory. This view will provide a form to upload images.

<!DOCTYPE html>
<html>

<head>
    <title>Image Upload</title>
    <style>
        form {
            margin: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
        }

        input[type="file"] {
            margin-bottom: 10px;
        }

        button[type="submit"] {
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }

        div[style="color: red"] {
            margin-top: 10px;
        }

        table {
            margin: 20px 20px 20px 0px;
            width: 100%;
            border-collapse: collapse;
            border: 1px solid black;
        }

        th {
            padding: 10px;
            background-color: #f2f2f2;
            text-align: left;
        }

        td {
            padding: 10px;
            border-bottom: 1px solid black;
        }

        img {
            width: 100px;
        }
    </style>
</head>

<body>
 @if (Session::has('success'))
            <div class="success-message fade-out">{{ Session::get('success') }}</div>
        @endif
    <form action="{{ route('image.upload') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <label for="image">Choose an image:</label>
        <input type="file" name="image" id="image">
        <button type="submit">Upload</button>
        @if ($errors->has('image'))
            <div style="color: red">{{ $errors->first('image') }}</div>
        @endif
    </form>
    @foreach ($images as $image)
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Image</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>{{ $image->id }}</td>
                    <td> <img style="width: 100px" src="{{ asset('storage/' . $image->image_path) }}"
                            alt="Original Image"></td>
                    <td> <a href="{{ route('image.show', ['id' => $image->id]) }}">View Image Details</a></td>
                </tr>
            </tbody>
        </table>
    @endforeach
</body>

</html>

Create another Blade view file named “show.blade.php” to display the original and resized images.

<!DOCTYPE html>
<html>
<head>
    <title>Show Images</title>
</head>
<body>
    <h1>Original Image</h1>
    @if (session('success'))
    <div class="success-message">{{ session('success') }}</div>
@endif
    <img src="{{ $originalImagePath }}" alt="Original Image">

    <h1>Resized Image</h1>
    <img src="{{ $resizedImagePath }}" alt="Resized Image">
</body>
</html>

Step 7: Linking the Storage:

Laravel’s storage system allows you to store and retrieve files. To make these files accessible from the web, you need to create a symbolic link between the public/storage directory and the storage/app/public directory.

In your terminal, run the following command:

php artisan storage:link

This will create a symbolic link named storage in your public directory.

Step 8: Defining Routes:

Open the routes/web.php file and define the necessary routes for your application:

<?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 and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/upload', [ImageController::class, 'showUploadForm'])->name('image.upload.form');
Route::post('/upload', [ImageController::class,'uploadAndResize'])->name('image.upload');
Route::get('/images/{id}', [ImageController::class,'showImages'])->name('image.show');

Here, we’re defining three routes:

  1. A GET route to display the image upload form.
  2. A POST route to handle image uploading and resizing.
  3. A GET route to display the original and resized images.

Step 9: Wrapping Up

With all components in place, your image resizer web app is ready to use. Users can upload images using the upload form, which will be automatically resized. The “show” view allows users to see both the original and resized versions of the uploaded image.

Conclusion:

Congratulations! You’ve successfully built an image resizer web app using Laravel. This functionality can be a valuable addition to various projects, from galleries to social media platforms. By following this guide, you’ve learned how to set up the project, install dependencies, create models, tables, controllers, views, and routes to achieve a seamless image resizing experience.

image resize in laravel
image resize in laravel

Our Recommendation

Avatar of Akhand Pratap Singh

Akhand Pratap Singh

Greetings and a warm welcome to my website! I am Akhand Pratap Singh, a dedicated professional web developer and passionate blogger.

Related Post

Leave a Comment





Newsletter

Subscribe for latest updates

We don't spam.

Loading

Categories