If you are uploading the large image file in the server then it will take up extra spaces of the storage. Then why don’t we resize image before upload. So, that it will reduce image size and will occupy less storage. If the webpage contains the low size image, then it will load fast in the webserver. So, if you resize image before upload, it will make your webpage optimized. I have already shared a tutorial on Image and Files upload in Laravel 6. But, today in this article, I am gonna show you how you can resize image before upload in the Laravel 6.
Prerequisites
For creating this project, you must have a system ready with the following-
- PHP version >=7.3.9
- MySQL (version > 5)
- Apache/Nginx Server
- A Code Editor (VS Code, PHP Storm)
I am gonna use VS Code here for this project.
Drag and Drop File Upload in Laravel 6 Using Dropzone js
Create a New Project For Resize Image
If you don’t have any Laravel 6 project setup, then let’s do a fresh installation of Laravel 6. Open the command prompt and then enter the below command. It will install the Laravel 6 with the required libraries.
composer create-project --prefer-dist laravel/laravel laravel-resize-image
Here, you can see that the Laravel latest version is installing. So, just wait till it finishes the installation.
Now, you will have a directory of the project name laravel6-resize-image.
How to Implement Pagination in Laravel 6 with Example
Install Intervention Package
To resize image in Laravel 6, we’ll have to add a package named intervention. This package is available in the composer. So, we can install it easily inside our project. You will have to navigate inside the project folder and then hit enter the below command.
composer require intervention/image
This command will add the required dependencies that are necessary for image resizing.
Once the required packages are added to your project, just move ahead to the next step.
How to Use AJAX in Laravel 6 with ToDo Application
Add Providers and Aliases For Intervention Package
In the next step, you will have to add the providers and aliases in the config/app.php.
'providers' => [
'Intervention\Image\ImageServiceProvider',
],
'aliases' => [
'ImageResize' => 'Intervention\Image\Facades\Image',
],
Once you are done with the above steps, let’s move to the database.
Create and Configure Database
In this application, I am going to upload and resize image. But after uploading, I am going to save the image details into the database. So, for this, I will create a database in MySQL.
CREATE DATABASE laravel6_resize_image;
Once, you have created the database, let’s configure it inside the .env file of your project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel6_resize_image
DB_USERNAME=root
DB_PASSWORD=root
Just, replace the database credentials with the above snippet.
How to Integrate Laravel 6 Application with Firebase
Create a Model and Migration
Now, we will create a Model for the image upload. So that we can store the resized image details into the database.
In the terminal hit the below command. It will create a Model with a migration file.
php artisan make:model Image --migration
After creating the model and migration file, let’s make some changes in the create_images_table.php file.
// create_images_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('img');
$table->string('thumbnail_img');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
You can add more fields according to the requirement. But currently, we no need to add more.
Laravel 6 Custom Login and Registration with Session
Migrate Table
Subsequently, we will migrate the table schema so that our tables can be created. Hence, run the migrate command to create the table into the database.
php artisan migrate
Create a Controller For Resize Image
To resize image in Laravel 6, we will have to write some codes. So for this, I will create a controller.
php artisan make:controller ImageResizeController
Now, paste the below code there.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use ImageResize;
use App\Image;
class ImageResizeController extends Controller
{
public function index() {
return view('fileUpload');
}
public function store(Request $request) {
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->extension();
$destinationPath = public_path('/uploads/thumbnail');
$img = ImageResize::make($image->path());
// --------- [ Resize Image ] ---------------
$img->resize(150, 100, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input['imagename']);
// ----------- [ Uploads Image in Original Form ] ----------
$destinationPath = public_path('/uploads/original');
$image->move($destinationPath, $input['imagename']);
// store into database table
Image::create(['img' => $input['imagename'], 'thumbnail_img' => $input['imagename']]);
return back()
->with('success', 'Image Uploaded successfully')
->with('imageName', $input['imagename']);
}
}
In the above controller, I have created two functions. The first is for loading the View that I will design here.
The second function will read the file from the form. Then, it will resize image. After resizing it will move to the destination folder. Also, it will upload the original image to another folder. So, here we will have two different copies of the uploaded image. One is for the original image and another is for the resized image.
How to Send Email in Laravel 6 Via Gmail Using SMTP
Create Routes
For calling the above functions, we’ll need the routes. So, in the routes/web.php just add the below routes.
Route::get('image-upload', 'ImageResizeController@index');
Route::post('upload', 'ImageResizeController@store');
Create Views
At the final step, we will have to create a view in which we’ll add the form containing the input type file. The image will be uploaded from this view. So, just create a blade file in the resources/view folder.
In my case, I’ve created a view with the name fileUpload.blade.php.
<!-- fileUpload.blade.php -->
<!doctype html>
<html lang="en">
<head>
<title>Image Resize in Laravel 6 Before Upload</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
@if ($response = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $response }}</strong>
</div>
<div class="row">
<div class="col-md-12">
<strong>Original Image:</strong>
<br/>
<img src="/uploads/original/{{ Session::get('imageName') }}" class="img-fluid" />
</div>
</div>
<div class="row">
<div class="col-md-12">
<strong>Resized Image:</strong>
<br/>
<img src="/uploads/thumbnail/{{ Session::get('imageName') }}" />
</div>
</div>
@endif
<form method="post" action="{{ url('upload') }}" enctype="multipart/form-data">
@csrf
<div class="card shadow">
<div class="card-header bg-primary">
<h4 class="card-title text-white"> Image Resize in Laravel 6 Before Upload </h4>
</div>
<div class="card-body">
<div class="form-group">
<label for="image"> Image </label>
<input type="file" name="image" id="image" class="form-control">
{!! $errors->first('image', '<small class="text-danger">:message</small>') !!}
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
In the above snippet, I have created a form using bootstrap. The form action has set for a route that has defined in the route section. So, when the form will submit, it will call that function. Also, I have added the image validation. So, if the validation fails, the error will be displayed below the input field.
Save and run the application using the artisan command.
php artisan serve
The Laravel application will be started on the default port 8000. You can access it from the browser. So just hit the below URL in the browser.
http://localhost:8000/image-upload
The above URL will load the view as shown below.
If you hit the upload button without choosing the file then it will give the validation error.
Now choose a file and click on the upload button. If you got a success message then it means your file has been resized and uploaded. In the below result, you can see here, there is a preview of the uploaded image. The image has been resized and in the preview, you can see the original image and the resized image.
You can check in the project folder – public/uploads/original for the uploaded file.
Similarly, the resized image has been uploaded in the thumbnail folder.
Laravel 6 REST API For ToDo Application with Passport Auth
Conclusion
Bingo! we have successfully created functionality for resizing the image in Laravel 6. The original image and the resized image both are in the separate folder. So, you can resize any kind of image before upload in Laravel 6. This will make optimized to your webpage from loading large size of images. I hope, this tutorial will help you a lot to free up the storage space.
Leave a Reply