Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to create multiple size thumbs from image in laravel

How to create multiple size thumbs from image in laravel 9 ?

Aman Jain, May 14, 2022February 22, 2024

Resizing images can be a best performance booster for any application since this will load the proper size images. In this article i will show you to create multiple size thumbs from image in laravel using intervention package. Big size of image can reduce the performance of the application therefor its an important aspect to reduce the size of image with proper size according to container so we can keep the original size and reduce the image size in thumbs.

In this article i will use PHP intervention/image package to create multiple size thumbs from image in laravel 9 . This package has several methods to reduce, Resize , effects and many more. But in this topic we will cover create multiple size thumbs from image .

Intervention Image is an open source PHP image handling and manipulation library. This library usage two most common image processing libraries GD Library and Imagick.

In this example we will create a simple example to create multiple size thumbs while uploading in laravel. For this we will create a database, table, model, controller and simple view for html

Let’s start compress and reduce image size while uploading in laravel 8 / 9 with simple step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

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

You can also read this to start with new project

Step 2 : Install the package

I assume the you have already installed the laravel and basic connection of it like database connection and composer.

Now install the package using composer in laravel root directory, open the terminal in laravel root directory and run below command to install intervention/image the package. This package has good stars on github and has lot of fan base of artisans

composer require intervention/image

Register Providers & Aliases

Add the following code the config/app.php file

'providers' => [
  .......
  .......
  .......
   Intervention\Image\ImageServiceProvider::class,
 
 ],  
 'aliases' => Facade::defaultAliases()->merge([
        // 'ExampleClass' => App\Example\ExampleClass::class,
        'Image' => 'Intervention\Image\Facades\Image'
    ])->toArray(),

Step 3 : Create a table and model

Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;
    
}

and migration file database/migrations/timestamp_create_articles_table.php

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();
            $table->string('image');
            $table->timestamps();
        });
    }

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

and then migrate the migration

php artisan migrate

Step 3 : Create controller

Let’s create a controller and add a methods showArticle, createThumbs and addArticle

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
    public function showArticle(Request $request){

        $articles = Article::all();
        return view('articles.article',['articles'=>$articles]);
     }
 
     function addArticle(Request $request){
        
        $validator = Validator::make($request->all(),[
                        'title' => "required",
                        'email' => "required|email",
                        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
                    ]);
        if ($validator->fails()) 
        {
            return redirect()->back()->withInput()->withErrors($validator->errors());
        }
        
        $file = $request->file("image");
        $destination="uploads/images";
        $filePathForSave=storage_path('app/'. $destination);
        $fileName = time().rand(111111111,9999999999).'.'.$file->getClientOriginalExtension();
        
        $this->createThumbs($file,$fileName,$filePathForSave);
         //create a random file name with time
          
        $file->move($filePathForSave,$fileName);

         //  save image and name in database
           $Article=new Article();
           $Article->title=$request->title;
           $Article->email=$request->email;
           $Article->image=$destination."/".$fileName;
           $Article->save();
           return back()
             ->with('success','You have successfully created the article with compressed image.');
       
     }

    function createThumbs($file,$fileName,$destination="uploads/images",$sizes=[
         [50,50],
         [100,100]
    ]){
        foreach($sizes as $size){
             
            $destinationPath=$destination."/thumbs/".$size[0]."x".$size[1];
            
            if (!\File::exists( $destinationPath)) {
                \File::makeDirectory($destinationPath, 0755, true);
            }
            
            \Image::make($file->getRealPath())->resize($size[0], $size[1], function ($constraint) {
                $constraint->aspectRatio();
            })
            ->save($destinationPath."/".$fileName); 

        }
    }
}

In above code we used createThumbs method to create multiple size thumbs which accepts four parameters first file object, second filename, third folder destination to save and last list of sizes

function createThumbs($file,$fileName,$destination="uploads/images",$sizes=[
         [50,50],
         [100,100]
    ]){
        foreach($sizes as $size){
             
            $destinationPath=$destination."/thumbs/".$size[0]."x".$size[1];
            
            if (!\File::exists( $destinationPath)) {
                \File::makeDirectory($destinationPath, 0755, true);
            }
            
            \Image::make($file->getRealPath())->resize($size[0], $size[1], function ($constraint) {
                $constraint->aspectRatio();
            })
            ->save($destinationPath."/".$fileName); 

        }
    }

First we fetched the image from request then created a random file name with timestamp so we can store a unique file name. After that we used File class to create the folder recursively with permission 0755 and then with \Image::make and resize method we resized the image and saved to the deastination. We also save the original image using move methods.

Step 4 : Create Symblink for Storage

This is an important step and i suggest you to not skip, if you are going to show images in your website because you must need to access the image to show it on website so open config\filesystems.php and add public_path('uploads') => storage_path('app/uploads') to links block

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'public'),
    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        ],

    ],
    'links' => [
        public_path('storage') => storage_path('app/public'),
        public_path('uploads') => storage_path('app/uploads'),
    ],

];

Since we are using in our controller this code

$destinationPath= '/uploads/images';
         
$storageDestinationPath=storage_path('app'.$destinationPath);

so we created a Symblink as

 public_path('uploads') => storage_path('app/uploads'),

Now run artisan command to run Symblink

php artisan storage:link

NOTE: If you are using php artisan serve and virtual host to serve your application the above method will work perfect but in case you are putting your public/index.php in root folder then you need to add public in URL. Example

URL for php artisan serve and virtual host will be and this will work perfectly

http://localhost:8000/uploads/images/16525039733751202249.png 

and you are putting your public/index.php in root folder then you need to add public in URL

http://localhost/projectname/public/uploads/images/16525039733751202249.png 

Or for shared hosting

Route::get('/artisan-link', function () {
    Artisan::call('storage:link');
});

Step 4 : Create View File

Now, show the upload form in view file and also show the list of resized images

resources/views/articles/article.blade.php

<!DOCTYPE html>
<html>

<head>
    <title>How to create multiple size thumbs from image in laravel 9 ? - readerstacks.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body>
    <div class="container">

        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2>How to create multiple size thumbs from image in laravel 9 ? -readerstacks.com</h2>
            </div>
            <div class="panel-body">

                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <strong>{{ $message }}</strong>
                </div>

                @endif
                <br><br>
                <form action="{{ url('add-article') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="row">

                        <div class="col-md-4">
                            <label>Title</label>
                            <input type="text" placeholder="Title" name="title" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Email</label>
                            <input type="email" placeholder="Email" name="email" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Image</label>
                            <input type="file" placeholder="Image" name="image" id="imgInp">
                        </div>
                    </div>
                    <div class="row">



                        <div class="col-md-6">
                            <button type="submit" class="btn btn-success">Upload</button>
                        </div>

                    </div>
                </form>
                <br>
                <h2>All Articles</h2>
                <table class="table">
                    <tr>
                        <th>Name</th>
                        <th>Image</th>

                    </tr>
                    @foreach( $articles as $article)
                    <tr>
                        <td>{{$article->title}}</td>
                        <td>
                             <!-- in case of you are putting index.php in root folder -->
                             <!-- <img height="100" width=100 src="{{asset('public/'.$article->image)}}" /> -->
                           
                            <img  src="{{asset($article->image)}}" />
                            <img  src="{{asset(str_replace('uploads/images','uploads/images/thumbs/50x50',$article->image))}}" />
                            <img  src="{{asset(str_replace('uploads/images','uploads/images/thumbs/100x100',$article->image))}}" />
                            
                        </td>
                    </tr>
                    @endforeach
                </table>
            </div>
        </div>
    </div>
</body>

</html>


here we used {{asset($article->image)}} to render the image in web page.

Step 4: Create two routes in routes/web.php

One route for preview the html and another route for upload and compress the image.

routes/web.php

<?php

use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;


Route::get('/articles',[ArticleController::class,"showArticle"]);
Route::post('/add-article',[ArticleController::class,"addArticle"]);

I

Results Screenshot:

Screenshot 2022 05 14 at 6.21.06 PM

I hope it will help you to implement form image uploading with compress. you can also read article to How to compress and reduce image size while uploading in laravel 8 / 9 ?

Related

Php Laravel Laravel 9 imageinterventionlaravelresize

Post navigation

Previous post
Next post

Related Posts

Php How to Use Bootstrap 5 in Laravel 9

How to Use Bootstrap 5 in Laravel 9 ?

May 30, 2022May 30, 2022

Bootstrap is a UI framework to enhance the beauty of website. In this tutorial i will show you to use Bootstrap 5 in laravel. Using the bootstrap we can enable multiple UI multiple functionality like we can show amazing buttons , card, input etc. Even with JavaScript library of bootstrap…

Read More
Javascript Laravel Customized Autocomplete JQuery UI

Laravel Customized Autocomplete JQuery UI

July 12, 2022July 12, 2022

Laravel Customized Autocomplete JQuery UI is useful when we want live search of bulk data. Autocomplete search is mostly work of javascript and when we want to fetch live data from database then we require the intervention of laravel to provide the data in json response. In this tutorial we…

Read More
Php Show Validation Error Message

How to Show Validation Error Message in Laravel ?

November 10, 2023March 16, 2024

In this article i will explain you to show validation error message in laravel. One crucial aspect of web development is handling form validation and displaying error messages to users effectively. In this guide, we will delve into the intricacies of showing validation error messages in Laravel, ensuring a smooth…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version