CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   Laravel   Laravel Resize Image On the Fly Using PHP GD Library & I ...

Laravel Resize Image On the Fly Using PHP GD Library & Intervention Image

February 3, 2018 by SNK

laravel image resize on the fly

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.

  1. Using PHP image processing generation or GD library/imagick which is availabel in PHP version 4 or higher.
  2. 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.

  1. Create index.php inside resources/views folder
  2. Create new controller named AdminController.php just get it through the php artisan command.
  3. Also $ php composer.phar require intervention/image if you are on mac or composer 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 :-

index.blade.php
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.

web.php
PHP
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.

Return Index View
PHP
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.

AdminController UploadImage Function
PHP
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.

Admin Controller Image Reisze Function
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

Registering Image Intervention Package to Service Providers

Similarly, add an aliases in the bottom too.

'Image' => Intervention\Image\Facades\Image::class

Registering Alises of the Intervention Image

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.

Importing Intevention Image on Top of Controller

Take a look at the function below, i am just going to slightly modify the upload Image function using intervention image features.

Upload Image Function Using Intervention Image Features
PHP
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.

Maintain Aspect Ratio
PHP
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

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

Web.php
PHP
1
2
Route::get('/', 'AdminController@index');
Route::post('/upload', 'AdminController@uploadImage')->name('upload.resized.image');

app/http/Controllers/AdminController

AdminController.php
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
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.

 

SHARE ON
Buffer

Enjoyed this article?

Like us on

Laravel PHP jcrop laravel laravel 5 crop image laravel crop image before upload

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.