🚀 Unleashing the Power of AWS Lambda for Image Compression in Laravel Application 🚀
Tags: lamda, aws, serverless, laravel
Published: 2024-02-27 04:18:08

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:

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

```

**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:

```bash
composer require bref/bref

```

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

```

**Step 4: Upload Image to S3 in Laravel Controller**

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

```php
// 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
    }
}
```

**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:**

```python
# Example Lambda Function Code

import json
import boto3
from PIL import Image
from io import BytesIO

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # Get the S3 bucket and key from the event
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    # Download the image from S3
    response = s3.get_object(Bucket=bucket, Key=key)
    image_data = response['Body'].read()

    # Compress the image using Intervention Image
    compressed_image_data = compress_image(image_data)

    # Upload the compressed image back to S3
    compressed_key = 'compressed/' + key
    s3.put_object(Body=compressed_image_data, Bucket=bucket, Key=compressed_key)

    return {
        'statusCode': 200,
        'body': json.dumps('Image compression successful!')
    }

def compress_image(image_data):
    image = Image.open(BytesIO(image_data))
    # Apply your compression logic using Intervention Image or any other library
    # Example: image.thumbnail((500, 500), Image.ANTIALIAS)

    # Save the compressed image to BytesIO
    compressed_image_data = BytesIO()
    image.save(compressed_image_data, format='JPEG')  # Adjust format based on your requirements

    return compressed_image_data.getvalue()

```

**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:

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

```

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