How to Compress Image Size in Laravel 11?
In this article, I will show you how to optimize image using spatie/image in laravel 11 application.
We will use the spatie/image Composer package to compress image size in laravel 11. The spatie/image Composer package is a PHP library used for image manipulation. It allows users to resize, crop, and apply filters to images easily. With simple syntax, it supports various formats like JPEG, PNG, and GIF. It's often used in web development to handle and edit images before displaying them on websites. The package is well-documented and integrates seamlessly with popular frameworks like Laravel.
In this example, we will install the spatie/image Composer package. spatie/image provides methods to optimize image size using the `load()` and `optimize()` methods. We will create a simple form with the file input field. You can choose an image, and then you will see a preview of the original image.
Step for How to Optimize Image Size in Laravel 11?
- Step 1: Install Laravel 11
- Step 2: Install spatie/image Package
- Step 3: Create Routes
- Step 4: Create Controller File
- Step 5: View File and Create Upload directory
- Run Laravel App
So, let's follow the below steps to generate a thumbnail image in the Laravel 11 application.
Step 1: Install Laravel 11
This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Install spatie/image Image Package
In the second step, we will install spatie/image for compress image. So, first, fire the command below in your CMD or terminal:
composer require spatie/image
Now, we also need to install image optimization tools in your system, so let's install it to your system as well:
Install all the optimizers on Ubuntu/Debian:
sudo apt-get install jpegoptim
sudo apt-get install optipng
sudo apt-get install pngquant // For PNG Image
sudo npm install -g svgo
sudo apt-get install gifsicle
sudo apt-get install webp
sudo apt-get install libavif-bin # minimum 0.9.3
Install all the optimizers on MacOS:
brew install jpegoptim
brew install optipng
brew install pngquant
npm install -g svgo
brew install gifsicle
brew install webp
brew install libavif
Install all the optimizers on Fedora/RHEL/CentOS:
sudo dnf install epel-release
sudo dnf install jpegoptim
sudo dnf install optipng
sudo dnf install pngquant
sudo npm install -g svgo
sudo dnf install gifsicle
sudo dnf install libwebp-tools
sudo dnf install libavif-tools
Step 3: Create Routes
In this step, we will add routes and a controller file. So first, add the below route in your routes.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');
Step 4: Create Controller File
Now, it is required to create a new ImageController for image upload and compress image. So, first, run the command below:
php artisan make:controller ImageController
After this command, you can find the ImageController.php file in your app/Http/Controllers directory. Open ImageController.php file and put below code in that file.
Make sure you have created "images" folder in the public folder.
app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Spatie\Image\Image;
class ImageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('imageUpload');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request): RedirectResponse
{
$this->validate($request, [
'image' => ['required'],
]);
$imageName = time().'.'.$request->image->extension();
Image::load($request->image->path())
->optimize()
->save(public_path('images/'). $imageName);
return back()->with('success', 'You have successfully upload image.')
->with('image', $imageName);
}
}
Step 5: View File and Create Upload directory
Okay, in this last step, we will create the imageUpload.blade.php file for the photo upload form and manage error messages and also success messages. So first, create the imageUpload.blade.php file and put the code below:
resources/views/imageUpload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Compress Image Example - ItSolutionStuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Compress Image Example - ItSolutionStuff.com</h3>
<div class="card-body">
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
<img src="images/{{ Session::get('image') }}">
@endif
<form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label class="form-label" for="inputImage">Image:</label>
<input
type="file"
name="image"
id="inputImage"
class="form-control @error('image') is-invalid @enderror">
@error('image')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/image-upload
Output:
Original Image: 1.1 MB
Compressed Image: 260KB
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 11 Integrate Authorize.net Payment Gateway Example
- Laravel 11 Custom Forgot Password Tutorial
- How to Install and Use Trix Editor in Laravel 11?
- Laravel 11 Product Add to Cart Functionality Example
- Laravel 11 MongoDB CRUD Application Tutorial
- Laravel 11 CORS Middleware Configuration Example
- Laravel 11 Socialite Login with Slack Account Example
- Laravel 11 Like Dislike System Tutorial Example
- Laravel 11 PayPal Payment Gateway Integration Example
- How to Install Bootstrap 5 in Laravel 11 with Vite?
- Laravel 11 Remove Public from URL Example
- Laravel 11 JQuery Load More Data on Scroll Example
- Laravel 11 Custom Validation Error Message Example
- Laravel 11 Restrict User Access from IP Address Example