How To Resize Image In Laravel 10? Image Intervention Guide

Laravel Image Resize Project in 10 Minutes

Last Updated On - August 2nd, 2024 Published On - Feb 16, 2023

Overview

Image intervention project is used to resize any image to a fixed resolution while maintaining the aspect ratio. It is generally used to make images of similar size so that the web page looks good and loads quickly as the more prominent images take time to load. In this post, we’ll learn how to resize image in Laravel(Php) with the help of the Laravel intervention/image package.

Architecture

For this project, I will be using the Laravel PHP framework as it provides a robust set of tools and features for building web applications, including image resizing. Laravel has a built-in image manipulation library called “Intervention Image” that we can use to resize and manipulate images.

To store the images, I will be saving them in the project directory itself but you can use Amazon S3, which is a scalable and secure cloud storage service. Using S3 will allow you to easily store and retrieve images without having to worry about managing your own storage infrastructure.

To handle the user interface, I will be using Bootstrap, a popular front-end framework that provides a set of pre-designed UI components that we can use to build a responsive and user-friendly interface.


Also Read: Creating Perfect Image Copies in Laravel: Resize, Center, and Save to Azure Blob!


Steps To Implement

  • Create a Laravel project using the following command:
composer create-project --prefer-dist laravel/laravel image-resize-project
  • Install the Intervention Image package using Composer:
composer require intervention/image
  • After installation, add the Intervention Image Service Provider to your config/app.php file:
'providers' => [
    // ...
    Intervention\Image\ImageServiceProvider::class,
],

  • Add the Intervention Image facade to the aliases array in config/app.php:
'aliases' => [
    // ...
    'Image' => Intervention\Image\Facades\Image::class,
],

  • Create a controller to handle the Resize image logic using the following command:
php artisan make:controller ResizeController
  • Create a folder inside public directory named as thumbnail(in this folder we’re going to save the resized image)
  • In the ResizeController class, create 2 methods index() and resizeImage() to load the upload image form and to resize & save the image respectively:
    public function index()
    {
        return view('resize-image');
    }

    public function resizeImage(Request $request)
    {
        // Get the uploaded image from the request
        $image = $request->file('image');

        // Validate the image for acceptable image formats and max upload size(Max upto 5MB)
        $this->validate($request, [
            'image' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:5120',
        ]);

        // Generate a unique filename for the uploaded image
        $input['image'] = time().'.'.$image->getClientOriginalExtension();
        
        // Set the path to save the resized image
        $thumbnailPath = public_path('/thumbnail');
        
        // Use the Intervention Image package to resize the image and save it to the desired directory
        $imgFile->resize(240, 240, function ($constraint) {
            $constraint->aspectRatio();
        })->save($thumbnailPath.'/'.$input['image']);

        //Send the user back to the upload page with success message and image URL in session
        return back()
            ->with('success','Image has successfully uploaded.')
            ->with('imageName',url('thumbnail/'.$input['image']));
    }

Let’s break down each part of the resizeImage() function:

  1. The resizeImage() function takes a Request object as its argument. This object contains the uploaded image that we want to resize.
  2. We get the uploaded image from the request using the file() method.
  3. We generate a unique filename for the uploaded image using the current timestamp and the original file extension.
  4. We set the path where we want to save the resized image. In this case, we save it to the public/images directory.
  5. We use the Intervention Image package to resize the image. We first create an Intervention\Image\Image object by passing the uploaded image’s path to the make() method. We then call the resize() method on the Image object and specify the desired width and height. We also use the aspectRatio() method to maintain the aspect ratio of the image. Finally, we save the resized image to the path we specified.
  6. If the image is resized successfully, we return a success message to the user.

Also Read: How To Setup Real-Time Synchronization with Laravel 11, Pusher, & Angular 18?


  • Create resize-image.blade.php file inside resources->views. Create a form to upload the image:
<div class="container mt-5" style="max-width: 550px">
    <h2 class="mb-5">Image Resize Demo</h2>
    <form action="{{route('resizeImage')}}" method="post" enctype="multipart/form-data">
        @csrf
        @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <strong>{{ $message }}</strong>
            </div>

            <div class="col-md-12 mb-3">
                <strong>Resized Thumbnail Image:</strong><br/>
                <img src="{{ Session::get('imageName') }}" width="240px" />
            </div>
        @endif

        <div class="form-group row">
            <div class="col-md-12 mb-3">
                <div id="imageprev" class="mt-3"></div>
            </div>
        </div>
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        <div class="custom-file">
            <input type="file" name="image" class="custom-file-input" id="chooseFile">
            <label class="custom-file-label" for="chooseFile">Select Image</label>
        </div>
        <button type="submit" name="submit" class="btn btn-outline-danger btn-block mt-4">
            Upload
        </button>
    </form>
</div>
  • Add the following routes in routes/web.php:
// Show image upload form
Route::get('/image-resize', [ResizeController::class, 'index']);
// Resize and save image in folder
Route::post('/resize', [ResizeController::class, 'resizeImage'])->name('resizeImage');
  • Run the project using the following command:
php artisan serve

This implementation will allow us to generate a newly resized image and store it in the thumbnail folder.


Also Read: How To Validate Location From IP & Zipcode Using Laravel 10?


Assumptions

  • For this project, I am assuming that the images being uploaded are not too large for the server to handle, and that we are only concerned with resizing images that are within a reasonable size range. If we need to resize very large images, we may need to consider using a distributed image processing system such as Apache Spark or Apache Flink.
  • The target server is running PHP 7.4 or higher.

Also Read: How to resolve Docker Setup Issues?


Deployment

Assuming you have a server with PHP and a web server (such as Apache or Nginx) installed, you can deploy the Image resizing project using the following steps:

  1. Copy the contents of the image-resizing directory to your server.
  2. Configure your web server to serve the contents of the public directory as the document root.
  3. Set the necessary environment variables on the server.


FAQs

Slow website due to large images? Fix it with Laravel image resizing!

Struggling with sluggish website loading times caused by bulky images? This guide unveils a quick and efficient Laravel solution for resizing images, optimizing your website speed and user experience.

Resize images on upload in Laravel – is it possible?

Yes, absolutely! This guide walks you through a step-by-step process to implement automatic image resizing during the upload process in your Laravel project.

Free image resizing tools available? Why use Laravel?

While free online image resizing tools exist, integrating resizing directly within your Laravel application offers several advantages:
Automation: Resize images automatically during upload, saving you time and effort.
Security: Maintain control over your image data within your Laravel environment.
Customization: Tailor image resizing parameters to your specific project needs.

Does image resizing affect image quality in Laravel?

Yes, image resizing can reduce quality, but with the right techniques, the impact is minimal. This guide explores various resizing methods in Laravel to achieve optimal compression with minimal quality loss.

Can I resize multiple images at once in my Laravel project?

Absolutely! The techniques outlined in this guide can be easily adapted to handle batch image resizing, saving you time when dealing with large numbers of images.

What file formats can be resized using this Laravel method?

This method supports popular image formats like JPEG, PNG, and GIF. You can potentially expand compatibility with additional formats through third-party Laravel packages.

Where are the resized images stored after processing in Laravel?

You have control over the storage location for resized images. This guide demonstrates saving them within your Laravel project directory or leveraging cloud storage solutions.

Is there a way to integrate this image resizing functionality into my existing Laravel project?

Yes! The concepts explained here can be seamlessly integrated into your current Laravel project. The guide provides clear instructions for implementation.

Looking to resize images on the client-side (user’s browser) instead of Laravel?

While this guide focuses on server-side resizing using Laravel, there are also JavaScript libraries that enable client-side image resizing for a potentially smoother user experience.

What if I need more advanced image manipulation functionalities beyond resizing in Laravel?

Laravel’s Intervention Image package offers a wide range of features beyond resizing. You can explore functionalities like cropping, watermarking, and more for comprehensive image manipulation.



TODO Next

  • Resize the image to Medium size i.e. 1024px width and use this image to further resize it to thumbnail size i.e. 240px