How to merge two images by using Laravel and intervention image? In this tutorial we will explain how to take two images, put them side by side and save as new image.

Here are the needed steps:

 

  • Step 1: Install and register intervention Image
  • Step 2: Prepare source images
  • Step 3: Create new blank image
  • Step 4: Add source images to new image
  • Step 5: Save combined image

 

Install and register intervention image

 

Installation of intervention image is very simple, just run in your terminal:

                    composer require intervention/image
                  

and after installation is finished open config/app.php and add this line in $providers array:

                    Intervention\Image\ImageServiceProvider::class
                  

and add this line in $aliases array:

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

 

Assign Intervention image to custom private variable

 

To achieve this we will include Intervention image in our class, create priv var and assign Intervention image to it and then your code editor will suggest all possible methods (and nested methods) names:

                    
use Intervention\Image\ImageManager;

private $imageManager;

class YourClass {
 public function __construct(
   ImageManager $imageManager
 ){
   $this->imageManager = $imageManager;
 }

}
                  

And now if you type $this->imageManager-> in your code editor (i.e. PHP Storm) it will automatically suggest you method names:

 

 

Prepare source images

 

So let's define two images which we are going to merge:

                    $img_left_local = public_path()."/user_photos/profile/image_left.jpg");
$img_right_local = public_path()."/user_photos/profile/image_right.jpg");

                  

 

Create new blank image

 

We will create new blank canvas image by using Laravel and inervention image. We will call our previously defined imageManager var and crate canvas 800x400px

                    $img_canvas = $this->imageManager->canvas(800,400);
        

                  

 

Add Source images to new image

 

Now we will use our source images and add them to our new canvas:

                    $img_canvas->insert(Image::make($img_right_local), 'top-left', 400, 0); 
$img_canvas->save(public_path()."/user_photos/vs/".$id_left."_vs_".$id_right.".jpg", 100);

$img_canvas->insert($this->imageManager->make($img_left_local), 'top-left');
$img_canvas->insert($this->imageManager->make($img_right_local), 'top-left', 400, 0); // move second image 400 px from left
        
                  

and now we can save our new combined image:

 

Save combined image

 

Now when we added our two images to canvas we can save this new image:

                     $img_canvas->save(public_path()."/user_photos/vs/".$id_left."_vs_".$id_right.".jpg", 100);