Resizing Image in Laravel

Image resizing is a common and essential task for most projects. It is considered good practice to resize the images according to their container’s dimensions so that the page performance is not affected much. We have an open-source library in Laravel called Intervention Image that helps to manipulate and handle PHP images. It retains the image quality while resizing and allows saving the resized image.

Installation

Assuming that the Laravel project is already created and running, we install the Intervention Image library for resizing the images. The least PHP version required for this library is 5.4.  So, we run the following command in the project’s root directory:

composer require intervention/image

It supports either GD library or Imagick for processing the images. So make sure one of it is available in the php environment of the project. If the GD library is missing, it can be installed by running the following command:

sudo apt-get install php7.0-gd (set the version accordingly, here php version 7.0)

Configuration

Once the library is successfully installed, go to the config/app.php file and add the service provider of the package to the $providers array as follows:

Intervention\Image\ImageServiceProvider::class

Also, add the facade to the $aliases array as below:

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

Now run the command php artisan config:cache to get the application cache cleared.

Example to follow the steps for image upload and resize

  1. Creating the storage link: Firstly, we create a storage directory under the public folder of the project using the following command:

    php artisan storage:link


    We will be storing the images under the /storage folder of the project but the images can be accessed in the /public/storage for displaying them in the frontend.
  2. Blade image input: Let’s created a form in the view file to save the user uploaded image.
    1. <form action="{{ route('PASS_ACTION_ROUTE') }}" method="post" enctype="multipart/form-data">
    2. @csrf
    3.   <div class="form-group">
    4.      <label for="image_file">Image Input</label>
    5.     <input type="file" name="image" id="image_file">
    6.   </div>
    7.   <button type="submit" class="btn btn-default">Submit</button>
    8. </form>
  3. Controller: In the controller, we need to add the facade “Image” so suppose we have an ImagesController then the code will be as below:
    1. <?PHP
    2.  
    3. namespace App\Http\Controllers;
    4.  
    5. use Illuminate\Http\Request;
    6. use Image;
    7. class ImagesController extends Controller
    8. {
    9.  
    10. }
  4. Image upload and store function: We create a function viz store to resize and save the image obtained in the request. Next, create an instance of the class Image using the make method for the image that we obtained in the POST request. Then we check for the current width and height of the image so that we can allow proportionate resizing of the image in order to prevent the image from getting blurred or stretched. Suppose in the following example we want to resize the image to 400×350 pixels, we set the value in the variables.

    1. public function store(Request $request)
    2. {
    3.     //filename along with the extension
    4.     $imagename&nbsp; &nbsp; = $image->getClientOriginalName();
    5.  
    6.     //image resize logic
    7.     $new_image = Image::make($image->getRealPath());
    8.     if($new_image != null){
    9.         $image_width= $new_image->width();
    10.         $image_height= $new_image->height();
    11.         $new_width= 400;
    12.         $new_height= 350;
    13.  
    14.         $new_image->resize($new_width, $new_height, function    ($constraint) {
    15.                $constraint->aspectRatio();
    16.         });
    17.  
    18. //saves the image into the public/storage/images folder
    19. $store_image=&nbsp; $new_image->save(public_path('images/' .$filename));&nbsp;
    20.  
    21. //stores the image into the /storage/app/public/images folder
    22. //$store_image=&nbsp; Storage::put('images/' .$filename, (string) $image->encode());
    23.  
    24. }
    We have used the aspect ratio function to prevent the image from cutting off or stretching. In case if one wants to hard crop the image then replace the code:
    1. $new_image->resize($new_width, $new_height, function ($constraint) {
    2.     $constraint->aspectRatio();
    3. });
    With
    1. $new_image->resize($new_width, $new_height);
    Here, we have the code to save the images into the storage directory (storage path) in the comment.

This library has one limitation that it cannot save an image into a new directory that is it cannot create a new directory and save the image, we need to have the directory created first.

Thus, we have created the functionality to resize the images and these images will help optimize the web page by avoiding the use of large size images.

Hope the article helps!
For more such articles, check our blog list.

Related Post

About the Author

Madhavi Gajjar

Gladly, working as a PHP/Laravel Developer at Regur Technology Solutions. Strives to explore, learn and grow technically and analytically. Loves crafting in free time.