Today in this article we are going to see how to resize image on the fly in laravel. We will go step by step process to resize the image in laravel. We will do it by using two methods, so you can use any of them as you wish.
- Using PHP image processing generation or GD library/imagick which is availabel in PHP version 4 or higher.
- Using Intervention Package by Oliver Vogel (if i am right, just found only one person in github).
Lets get started
We will create the necessary files first which will be used in both of the methods. So i assume you have fresh copy of laravel installed and have already created the file in the specified folders below.
- Create
index.php
insideresources/views
folder - Create new controller named
AdminController.php
just get it through the php artisan command. - Also
$ php composer.phar require intervention/image
if you are on mac orcomposer require intervention/image
if you are on windows. It will save the time later.
Image Resize By Using PHP Image Processing library (GD Library)
Step 1
We are going to create a form inside index.php
and upload the image and resizing will be done inside the function so make your form ready inside you PHP function or copy the codes below :-
1 2 3 4 5 6 7 8 9 10 |
<form action="{{ route('upload.resized.image') }}" method="POST" enctype="multipart/form-data"> {!! csrf_field() !!} <div class="form-group"> <label for="">Upload Image</label> <input type="file" class="form-control" name="image" accept="image/x-png,image/gif,image/jpeg" /> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-sm">Upload Image</button> </div> </form> |
Step 2
Next step is to configure routes. Go inside routes/web.php
and add these two lines of code.
1 2 |
Route::get('/', 'AdminController@index'); Route::post('/upload', 'AdminController@uploadImage')->name('upload.resized.image'); |
Step 3
Its time to write our functions. First create function inside AdminController to return our index view that we recently created inside resources/views
folder.
1 2 3 |
public function index() { return view('index'); } |
Step 4
Next step is to get the image from the form and resize. Lets write the functions for those.
1 2 3 4 5 6 7 |
public function uploadImage(Request $request) { header('Content-Type: image/jpeg'); $image = $request->image; $custom_width = 500; $custom_height = 500; $this->resizeImage($image_name,$custom_width,$custom_height, public_path('uploads/')); } |
In above step, first statement is setting headers what type of image we are converting into aka. jpeg, jpg,png or you can use any other. But here i am using jpg only.
In 2nd statement getting the image from the form.
In 3rd statement we are going to fetch the real path where our image is uploaded to.
In 4th statement we are just calling the resize image function and sending required parameters like image real path where it is located when we clicked browse.
Additionally, custom width and height is sent for the image that needs to be resized to and lastly, the location where the resized image will be uploaded to.
Lets create that function too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public function resizeImage($image_name, $new_width, $new_height, $saveLocation) { list($width, $height) = getimagesize($image_name); // user these function if you want to main the aspect ratio if($width > $height && $new_height < $height){ $new_height = $height / ($width / $new_width); } else if ($width < $height && $new_width < $width) { $new_width = $width / ($height / $new_height); } else { $new_width = $width; $new_height = $height; } // $thumb_image = imagecreatetruecolor($new_width, $new_height); $src = imagecreatefromjpeg($image_name); imagecopyresized($thumb_image, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagejpeg($thumb_image, $saveLocation.mt_rand(1,1000).".jpg"); } |
Now go to command prompt and type php artisan serve
and see if it works.
Lets dive into another method.
Image Resize By Using Intervention Image
I assume that you have already installed the image intervention package as mentioned earlier. Now its time to configure the package.
Note :- You can also check the official documentation at github if you have problem following the steps below.
Open config/app.php
and roll down to Laravel framework service providers section and add this line in the bottom.
Intervention\Image\ImageServiceProvider::class
Similarly, add an aliases in the bottom too.
'Image' => Intervention\Image\Facades\Image::class
If you have any trouble configuring package. You can always check the official documentation at github.
Step 1
Repeat all the process of previous method till step 3. We are going to have some changes in step 4. So, here i’ll be continuing directly from the step 4.
It is very easy to use intervention image package to resize images. You just have to use the class and implement in the functions. So add use Image
on top of your AdminController.php
below any namespaces.
Take a look at the function below, i am just going to slightly modify the upload Image function using intervention image features.
1 2 3 4 5 6 |
public function uploadImage(Request $request) { $image = $request->image; $original_name = $image->getClientOriginalName(); Image::make($image->getRealPath())->resize(500,500)->save(public_path('uploads/'.$original_name)); return redirect()->back(); } |
It’s damn easy. You can just resize and save image in just one line. Isn’t is amazing ?.
If you want to maintain the aspect ratio then just change the little bit of the code.
1 2 3 4 5 6 7 8 |
public function uploadImage(Request $request) { $image = $request->image; $original_name = $image->getClientOriginalName(); Image::make($image->getRealPath())->resize(500,500, function($constraint){ $constraint->aspectRatio(); })->save(public_path('uploads/'.$original_name)); return redirect()->back(); } |
This is it. Still Confused ?? Take a look at the full code
index.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Image Resize</title> <link rel="stylesheet" href="{{url('bootstrap')}}/css/bootstrap.min.css"> <link rel="stylesheet" href="{{url('bootstrap')}}/css/bootstrap-theme.min.css"> </head> <body> <div class="container" style="margin-top: 30px;"> <div class="col-md-offset-3 col-md-5"> <form action="{{ route('upload.resized.image') }}" method="POST" enctype="multipart/form-data"> {!! csrf_field() !!} <div class="form-group"> <label for="">Upload Image</label> <input type="file" class="form-control" name="image" accept="image/x-png,image/gif,image/jpeg" /> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-sm">Upload Image</button> </div> </form> </div> </div> <script src="{{url('bootstrap')}}/jquery-3.2.1.min.js"></script> <script src="{{url('bootstrap')}}/js/bootstrap.min.js"></script> </body> </html> |
routes/web.php
1 2 |
Route::get('/', 'AdminController@index'); Route::post('/upload', 'AdminController@uploadImage')->name('upload.resized.image'); |
app/http/Controllers/AdminController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Image; class AdminController extends Controller { public function index() { return view('index'); } /* public function uploadImage(Request $request) { header('Content-Type: image/jpeg'); $image = $request->image; $image_name = $image->getRealPath(); $custom_width = 500; $custom_height = 500; $this->resizeImage($image_name,$custom_width,$custom_height, public_path('uploads/')); return redirect()->back(); } */ public function resizeImage($image_name, $new_width, $new_height, $saveLocation) { list($width, $height) = getimagesize($image_name); // user these function if you want to main the aspect ratio if($width > $height && $new_height < $height){ $new_height = $height / ($width / $new_width); } else if ($width < $height && $new_width < $width) { $new_width = $width / ($height / $new_height); } else { $new_width = $width; $new_height = $height; } $thumb_image = imagecreatetruecolor($new_width, $new_height); $src = imagecreatefromjpeg($image_name); imagecopyresized($thumb_image, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagejpeg($thumb_image, $saveLocation.mt_rand(1,1000).".jpg"); } public function uploadImage(Request $request) { $image = $request->image; $original_name = $image->getClientOriginalName(); Image::make($image->getRealPath())->resize(500,500, function($constraint){ $constraint->aspectRatio(); })->save(public_path('uploads/'.$original_name)); return redirect()->back(); } } |
Test this code above and see if it works and meet your requirements. If you have any problem feel free to comment.
Leave a Reply