Resize Image in Laravel Using Intervention Image Library

Recently one of our readers asked how to resize the image in Laravel? Image resizing is a regular task for developers. The developers should do it correctly. It’s a good practice to resize the images matching their container size. It helps you to improve the performance of a page. In this article, we study how to resize the image in Laravel using the Intervention Image library.

Intervention Image is an open-source PHP library that provides an easy way to resize the images. Under the hood, this library uses GD Library and Imagick for image manipulation. Apart from resizing images, you can do much more with this library.

Why Should Resize Images?

Take the example of an image gallery. While working on a gallery, we normally display the small thumbnail in the listing. When someone clicks on the thumbnail, we show an original image. Here, the thumbnails are the resized version of the original image.

Let’s say your original image size is 500*500 and your container for the thumbnail is 200*200. In this case, you should resize the original image as per the thumbnail’s container size. It’s a bad practice to use a large image in a small container. It affects the website’s performance.

This is one example of why we should resize the images. There can be other scenarios as well. 

Having said that, let’s take a look at how to resize the image in Laravel using the Intervention Image library.

Installation

For getting started, you need to install the Intervention Image library in your Laravel project. You should have Composer installed on your system. Open the terminal in your project root directory and run the command below:

composer require intervention/image

After installing the library, open the config/app.php file and add the service provider and facade to it.

Add the service provider of this package to the $providers array.

Intervention\Image\ImageServiceProvider::class

Next, add the facade to the $aliases array.

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

Create View, Controller, Routes

To resize the image, we first need to store an image. Let’s store the images inside a storage directory. Head over to the terminal and create a symbolic link to the storage folder.

php artisan storage:link

This command creates a storage directory under the public folder. In the storage folder, we will upload a full and a thumbnail version of the images.

Define the below routes to call the view and submit form data on the server-side.

Route::get('image', 'ImageController@index');
Route::post('store', 'ImageController@store');

Next, create a form in the view file say image.blade. I am also adding code for the success message in the blade file.

@if (session('success'))
    <strong>
        {{ session('success') }}
    </strong>
@endif
<form action="{{ url('store') }}" method="post" enctype="multipart/form-data">
    @csrf
    Upload Image: <input type="file" name="profile_image" />
    <p><button type="submit" class="btn btn-default">Submit</button></p>
</form>

For the form action, I passed the store route. We will define the method mapped to this route in our controller. Create the ImageController using the Artisan command:

php artisan make:controller ImageController

Resize Image in Laravel

In the ImageController, it is required to add the Image facade of a library which we have added in the config/app.php file. This facade will be used to perform an image manipulation operation which is to resize images in our case.

By adding the facade, we are able to call functions of the Intervention Image library. In the below code, I will upload the image in two places. One is the original image under the profile_images folder. The second one is under the profile_images/thumbnail directory. I will first upload the original image in the thumbnail folder and then resize it.

The below code will go inside the ImageController file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Image;

class ImageController extends Controller
{
    public function index()
    {        
        return view('image');
    }

    public function store(Request $request)
    {
        if($request->hasFile('profile_image')) {
            //get filename with extension
            $filenamewithextension = $request->file('profile_image')->getClientOriginalName();
    
            //get filename without extension
            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
    
            //get file extension
            $extension = $request->file('profile_image')->getClientOriginalExtension();
    
            //filename to store
            $filenametostore = $filename.'_'.time().'.'.$extension;
    
            //Upload File
            $request->file('profile_image')->storeAs('public/profile_images', $filenametostore);
            $request->file('profile_image')->storeAs('public/profile_images/thumbnail', $filenametostore);
    
            //Resize image here
            $thumbnailpath = public_path('storage/profile_images/thumbnail/'.$filenametostore);
            $img = Image::make($thumbnailpath)->resize(400, 150, function($constraint) {
                $constraint->aspectRatio();
            });
            $img->save($thumbnailpath);
    
            return redirect('image')->with('success', "Image uploaded successfully.");
        }
    }
}

Here I am resizing the image proportionally. It will consider the aspect ratio while resizing the image so that the image will not be cut off. I have passed width as 400 and height as 150. You can change these values as per your requirement.

If you are looking for hard cropping then replace the below lines

$img = Image::make($thumbnailpath)->resize(400, 150, function($constraint) {
    $constraint->aspectRatio();
});
$img->save($thumbnailpath);

With

$img = Image::make($thumbnailpath)->resize(100, 100)->save($thumbnailpath);

After this, you will get the thumbnail with a dimension of 100*100.

I hope you may learn about resizing the image in Laravel using the Intervention Image library. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

4 thoughts on “Resize Image in Laravel Using Intervention Image Library

  1. Thanks for this tuto. It help mea lot.But is there any way to change the image background color? I’m working on an e-commerce and i want all the uploaded items images get a white background. I can do that by using PhotoShop in each image before uploading them but it’s little bit struggle. Coul you please provide me any solution ?

  2. after complete and write your code show this error-
    “The file “abc.jpg” was not uploaded due to an unknown error.”
    how to solve this?

Leave a Reply

Your email address will not be published.