Create Thumbnail in Laravel Using Intervention Image Library

While developing an application we need to create multiple versions of an image. These versions are like different sizes of a single image. We called it thumbnails. These thumbnails are used while displaying different image version depends on the container size. Showing image which fit as per container size will save bandwidth and improves a page load time. Showing large size image in a small container is a bad practice and can compromise the page load time. As a result, it’s a good practice of creating multiple thumbnails of an image and use it.

In this article, we study how to create a thumbnail in Laravel using Intervention Image library. This one is the free and one of the popular library for image manipulation. In the background, this library uses GD Library and Imagick for image manipulation.

For our tutorial, we will create 3 thumbnails – small, medium, large with sizes 150*93, 300*185, 550*340 respectively. Of course, users can change these sizes as per their needs.

Installation

For getting started, we need to install the Intervention Image library in Laravel. Open the terminal in your project root directory and run the command below:

composer require intervention/image

After installing the library, open config/app.php file and add the following lines.

Add the service providers for this package in the $providers array.

Intervention\Image\ImageServiceProvider::class

Add the facade to the $aliases array.

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

Next, we need to create a directory where we store all uploaded files. Head over to the terminal and run the command as follows:

php artisan storage:link

This command creates a storage directory(symbolic link) under the public folder.

Create a Thumbnail in Laravel

We all set with the basic setup and can now write the actual code. Let’s create a form in our view file.

<form action="{{ url('PASS_ACTION_URL') }}" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="exampleInputFile">File input</label>
        <input type="file" name="profile_image" id="exampleInputFile">
    </div>
    {{ csrf_field() }}
    <button type="submit" class="btn btn-default">Submit</button>
</form>

In our controller, we need to add our library facade ‘Image’ which we have added in our config/app.php file.

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Image;
 
class ImageController extends Controller
{
 
}

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

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;

        //small thumbnail name
        $smallthumbnail = $filename.'_small_'.time().'.'.$extension;

        //medium thumbnail name
        $mediumthumbnail = $filename.'_medium_'.time().'.'.$extension;

        //large thumbnail name
        $largethumbnail = $filename.'_large_'.time().'.'.$extension;

        //Upload File
        $request->file('profile_image')->storeAs('public/profile_images', $filenametostore);
        $request->file('profile_image')->storeAs('public/profile_images/thumbnail', $smallthumbnail);
        $request->file('profile_image')->storeAs('public/profile_images/thumbnail', $mediumthumbnail);
        $request->file('profile_image')->storeAs('public/profile_images/thumbnail', $largethumbnail);
 
        //create small thumbnail
        $smallthumbnailpath = public_path('storage/profile_images/thumbnail/'.$smallthumbnail);
        $this->createThumbnail($smallthumbnailpath, 150, 93);

        //create medium thumbnail
        $mediumthumbnailpath = public_path('storage/profile_images/thumbnail/'.$mediumthumbnail);
        $this->createThumbnail($mediumthumbnailpath, 300, 185);

        //create large thumbnail
        $largethumbnailpath = public_path('storage/profile_images/thumbnail/'.$largethumbnail);
        $this->createThumbnail($largethumbnailpath, 550, 340);
 
        return redirect('image')->with('success', "Image uploaded successfully.");
    }
}

In the above code, we store the image with 3 formats small, medium and large. Finally we are calling the method createThumbnail and passing them the required width, height. Let’s define the method below. It should go to the same Controller class.

/**
 * Create a thumbnail of specified size
 *
 * @param string $path path of thumbnail
 * @param int $width
 * @param int $height
 */
public function createThumbnail($path, $width, $height)
{
    $img = Image::make($path)->resize($width, $height, function ($constraint) {
        $constraint->aspectRatio();
    });
    $img->save($path);
}

Here we are resizing the image proportionally. Doing so, we keep the aspect ratio and image will not cut off.

If you are looking for hard crop then replace below lines

$img = Image::make($path)->resize($width, $height, function ($constraint) {
    $constraint->aspectRatio();
});
$img->save($path);

With

$img = Image::make($path)->resize($width, $height)->save($path);

We hope you understand how to create a thumbnail in Laravel using Intervention Image library. We would like to hear your thoughts in the comment section below.

Related Articles

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

Leave a Reply

Your email address will not be published. Required fields are marked *