Upload and Resize Multiple Images in Laravel

Apart from this blog, I am running a YouTube channel where I share video tutorials. Recently one of the subscribers asked about resizing multiple images in Laravel. They want to resize multiple images in one go. In this article, we study how to upload and resize multiple images in Laravel.

It’s always recommended to create a thumbnail version of the original image. You should store both versions of images on the server. Then depending on container size show the related images to the user. Displaying large images in a small container is a bad practice and affects the site’s performance.

To resize images, one can use the Intervention Image package. It’s an open-source library that allows users to manipulate images. I am going to use this library to create thumbnails from the original image.

Getting Started

First, install and configure the Intervention Image library into the Laravel project. Open the terminal in your project root directory and run the command for installation of a library:

composer require intervention/image

Once the library is installed, open the config/app.php file. Add service providers and a facade to it. Include the service provider of this package in the $providers array.

Intervention\Image\ImageServiceProvider::class,

Add the facade to the $aliases array.

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

Next, you’ll require a directory to store the images. Laravel Filesystem provides a public disk to store the files. The public disk contains files that are publicly accessible. You will find the uploaded files in the storage/app/public folder. To access these files on the web, you need to create a symbolic link from public/storage to storage/app/public.

Create this symbolic link using the command:

php artisan storage:link

This command would create a storage folder under the public directory. This is where we store the original images and their thumbnails.

In order to upload files on a server, you require a controller for calling a view and uploading the images on the server. Create the ImageController using the Artisan command:

php artisan make:controller ImageController

As we need to upload and resize the images, in the ImageController add two facades Image and Storage as follows.

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Image; //Intervention Image
use Illuminate\Support\Facades\Storage; //Laravel Filesystem
 
class ImageController extends Controller
{
 
}

By adding the Image facade, you are able to call resize functions of the Intervention Image library. The Storage facade will help you store images on the server.

Next, add the routes for the ImageController to the routes/web.php file.

Route::get('/image', 'ImageController@index');
Route::post('/image', 'ImageController@store');

Upload and Resize Images in Laravel

Let’s create a form to select files and send them to the server. The below code will go inside your view, say image.blade.

@if($message = Session::get('success'))
    <strong>{{ $message }}</strong>
@endif

<form action="{{ url('image') }}" method="post" enctype="multipart/form-data">
    @csrf
    Upload Image(s): <input type="file" name="profile_image[]" multiple />
    <p><button type="submit" name="submit">Submit</button></p>
</form>

In the form, I gave a name to the file input as profile_image[] which sends an array of files to the server. Also, I added an attribute multiple that allows you to select multiple files. To the action attribute, I passed the image route map with the post method.

Call this view from the index method of ImageController.

public function index()
{
    return view('image');
}

From the store() method, I will upload the image in two places. The original image will be stored under the storage/profile_images directory. The thumbnails will go inside the storage/profile_images/thumbnail folder. I first upload the original image in the thumbnail folder and then resize it.

public function store(Request $request)
{
    if ($request->hasFile('profile_image')) {
 
        foreach($request->file('profile_image') as $file){
 
            //get filename with extension
            $filenamewithextension = $file->getClientOriginalName();
 
            //get filename without extension
            $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
 
            //get file extension
            $extension = $file->getClientOriginalExtension();
 
            //filename to store
            $filenametostore = $filename.'_'.uniqid().'.'.$extension;
 
            Storage::put('public/profile_images/'. $filenametostore, fopen($file, 'r+'));
            Storage::put('public/profile_images/thumbnail/'. $filenametostore, fopen($file, 'r+'));
 
            //Resize image here
            $thumbnailpath = public_path('storage/profile_images/thumbnail/'.$filenametostore);
            $img = Image::make($thumbnailpath)->resize(400, 150, function($constraint) {
                $constraint->aspectRatio();
            });
            $img->save($thumbnailpath);
        }
 
        return redirect('image')->with('success', "Image(s) uploaded successfully.");
    }
}

Here I am resizing the images proportionally. It will keep the aspect ratio and the image will not cut off. I passed the width as 400 and the height as 150. You can change these values as per your requirement.

Go ahead and test it. You will get the resized version of chosen images under the storage/profile_images/thumbnail directory.

If you are looking for a hard crop then replace the below lines

$img = Image::make($thumbnailpath)->resize(400, 150, function($constraint) {
    $constraint->aspectRatio();
});
$img->save($thumbnailpath);

With

$img = Image::make($thumbnailpath)->resize(100, 100)->save($thumbnailpath);

This statement will hard crop the images to the dimension of 100*100.

I hope you understand how to upload and resize multiple images in Laravel. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “Upload and Resize Multiple Images in Laravel

Leave a Reply

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