DEV Community

Cover image for 🚀 Unleashing the Power of AWS Lambda for Image Compression in Laravel Application 🚀
Anwar Hossain
Anwar Hossain

Posted on • Updated on

🚀 Unleashing the Power of AWS Lambda for Image Compression in Laravel Application 🚀

Hey Dev community! 👋 Today, let's explore the magic of AWS Lambda and seamlessly integrate it into a Laravel application for uploading raw images to S3 and compressing them on the fly! 🖼️💡

Step 1: Set Up Your Laravel Application

Ensure you have a Laravel project up and running. If not, use Composer to create a new project:

composer create-project --prefer-dist laravel/laravel my-laravel-app

Enter fullscreen mode Exit fullscreen mode

Step 2: Configure AWS S3 Bucket

Create an S3 bucket on AWS to store both raw and compressed images. Note down your access key, secret key, and bucket name.

Step 3: Integrate AWS SDK in Laravel

Install the AWS SDK for PHP (Bref) using Composer:

composer require bref/bref

Enter fullscreen mode Exit fullscreen mode

Configure your AWS credentials in the .env file:

AWS_ACCESS_KEY_ID=your-access-key-id
AWS_SECRET_ACCESS_KEY=your-secret-access-key
AWS_DEFAULT_REGION=your-region # e.g., 'us-east-1'
AWS_BUCKET=your-s3-bucket-name

Enter fullscreen mode Exit fullscreen mode

Step 4: Upload Image to S3 in Laravel Controller

In your Laravel controller, use the AWS SDK to upload the raw image to S3:

// Example Laravel Controller

use Illuminate\Http\Request;
use Aws\S3\S3Client;

class ImageController extends Controller
{
    public function uploadToS3(Request $request)
    {
        $file = $request->file('image');
        $key = 'raw/' . $file->getClientOriginalName();

        $s3 = new S3Client([
            'region' => config('filesystems.disks.s3.region'),
            'version' => 'latest',
        ]);

        $s3->putObject([
            'Bucket' => config('filesystems.disks.s3.bucket'),
            'Key' => $key,
            'Body' => fopen($file, 'r'),
            'ACL' => 'public-read',
        ]);

        // Your logic for further processing or response
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Up AWS Lambda for Image Compression

Create an AWS Lambda function with permissions to access your S3 bucket. Implement image compression using the Intervention Image library.

Step 6: Trigger Lambda on S3 Object Creation

Configure an S3 event trigger to invoke your Lambda function whenever a new object is created in the bucket.

Lambda Function for Image Compression:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class ImageController extends Controller
{
    public function compressImage(Request $request)
    {
        // Get the S3 bucket and key from the request
        $bucket = $request->input('bucket');
        $key = $request->input('key');

        // Download the image from S3
        $s3 = Storage::disk('s3');
        $imageData = $s3->get($key);

        // Compress the image using Intervention Image
        $compressedImageData = $this->compressImage($imageData);

        // Upload the compressed image back to S3
        $compressedKey = 'compressed/' . $key;
        $s3->put($compressedKey, $compressedImageData);

        return response()->json(['message' => 'Image compression successful!'], 200);
    }

    private function compressImage($imageData)
    {
        // Load the image from raw data
        $image = Image::make($imageData);

        // Apply your compression logic here
        // Example: Resize the image to a maximum width/height of 500px while maintaining aspect ratio
        $image->resize(500, 500, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });

        // Save the compressed image to a temporary location in memory
        $compressedImageData = (string) $image->encode('jpg', 75); // Adjust format and quality as needed

        return $compressedImageData;
    }
}


Enter fullscreen mode Exit fullscreen mode

Access Compressed Image:

When you upload an image to the 'raw/' directory in S3, the Lambda function will be triggered.

The compressed image will be stored in the 'compressed/' directory.

To access the compressed image with lower size but the same quality, use the appropriate URL, for example:

https://your-s3-bucket.s3.amazonaws.com/compressed/your-image.jpg

Enter fullscreen mode Exit fullscreen mode

Now, your Lambda function will automatically compress images upon upload to S3, maintaining quality while reducing file size. Adjust the compression logic in the Lambda function as needed for your specific use case. Feel free to connect for more details or discussions! 🚀👨‍💻

AWSLambda #ImageCompression #Serverless #S3 #LaravelApplication #TechInnovation

Top comments (1)

Collapse
 
be41d45 profile image
Be41d45

Python or Laravel in sample? 😃