Laravel intervention image resize tutorial; This step-by-step guide shows you how to use the PHP intervention image package to upload and resize images in a Laravel application.
Image resizing is the act of modifying the image's dimensions; we visit a number of websites on a regular basis, whether it's social media, ecommerce, or any other site that requires us to upload images; we also have to build or generate thumbnail images on occasion.
As a result, we'll need to implement a file resizing capability to reduce the image's size and dimensions.
In this tutorial, we'll show you how to use the PHP intervention image package to severely resize a picture in a Laravel application. This package allows you to manage the image ratio.
Laravel 9 Image Resize with Intervention Image Example
Table of Content
- Step 1: Install Laravel App
- Step 2: Add Intervention Image Package
- Step 3: Register Image Intervention Package
- Step 4: Configure Controller
- Step 5: Add Routes
- Step 6: Set Up Blade View
- Step 7: Run Laravel Project
Install Laravel App
Let's start by setting up a new Laravel application; if you've previously set up the project, you can skip this step.
composer create-project --prefer-dist laravel/laravel laravel-demo
Go to app?s root:
cd laravel-demo
Add Intervention Image Package
This step explains how to install the PHP intervention image package into a Laravel application by typing command in the console and then executing it.
composer require intervention/image
Register Image Intervention Package
You must inject the package classes into the providers and aliases arrays in order to use the image intervention package in Laravel.
Open the config/app.php
file and make the changes listed below.
<?php
return [
......
$providers => [
......,
'Intervention\Image\ImageServiceProvider'
],
$aliases => [
......,
'Image' => 'Intervention\Image\Facades\Image'
]
]
Configure Controller
You must then run the following command to create a new controller file, in which we will implement the logic for handling the file upload and resizing features.
php artisan make:controller ResizeController
The blade view template is rendered into the view using the index() function. The resizeImage() function, on the other hand, validates the image, sets the maximum file upload limit, and saves the large image in uploads while storing the small and resized image in the thumbnail folder.
To store photographs and thumbnails, you'll need to establish two folders in the main public area. Create public/uploads and public/thumbnail directories in the same way.
Also, in the app/Http/Controllers/ResizeController.php file, edit the supplied code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;
class ResizeController extends Controller
{
public function index()
{
return view('welcome');
}
public function resizeImage(Request $request)
{
$this->validate($request, [
'file' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:2048',
]);
$image = $request->file('file');
$input['file'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/thumbnail');
$imgFile = Image::make($image->getRealPath());
$imgFile->resize(150, 150, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input['file']);
$destinationPath = public_path('/uploads');
$image->move($destinationPath, $input['file']);
return back()
->with('success','Image has successfully uploaded.')
->with('fileName',$input['file']);
}
}
Add Routes
Additionally, edit the routes/web.php file and add the routes to control GET and POST image resizing requests.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ResizeController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/file-resize', [ResizeController::class, 'index']);
Route::post('/resize-file', [ResizeController::class, 'resizeImage'])->name('resizeImage');
Set Up Blade View
Let's create a blade view to manage file resizing and uploads; we may use the default welcome blade template file as a starting point. We'll add Bootstrap CSS to this file, then use bootstrap to develop a basic file upload component.
Open the file resources/views/welcome.blade.php and paste the code below into it.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<title>Laravel Image Resize Example</title>
</head>
<body>
<div class="container mt-5" style="max-width: 550px">
<h2 class="mb-5">Laravel Image Resize Example</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>Grayscale Image:</strong><br/>
<img src="/uploads/{{ Session::get('fileName') }}" width="550px" />
</div>
@endif
@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="file" class="custom-file-input" id="chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<button type="submit" name="submit" class="btn btn-outline-danger btn-block mt-4">
Upload
</button>
</form>
</div>
</body>
</html>
Run Laravel Project
We've finished developing the picture resizing feature; now it's time to put it to the test. To run the application, use the following command.
php artisan serve
To run the app, go to the specified address in your browser.
http://127.0.0.1:8000/file-resize
Conclusion
The tutorial on how to upload and resize an image in Laravel is now complete; in this example, we demonstrated how to build a Laravel project from the ground up.
How to set up a controller and routes, install an intervention image package, and utilise the package's API to resize the image and show a preview.
I hope you will like the content and it will help you to learn Laravel 9 Image Resize & Upload with Intervention Image
If you like this content, do share.