Project: Lambda + S3 To Resize Images (Part 4)
Download the layer zip file by clicking here
Please save this on your local machine into Data Science Infinity/AWS/Lambda
Lambda Resize Code:
import boto3 from PIL import Image import io s3 = boto3.client('s3') def lambda_handler(event, context): source_bucket = event['Records'][0]['s3']['bucket']['name'] key = event['Records'][0]['s3']['object']['key'] image = get_s3_image(source_bucket, key) image = resize_image(image) save_image_to_s3(image, 'destination-bucket-name', key) def get_s3_image(bucket, key): response = s3.get_object(Bucket=bucket, Key=key) image = Image.open(io.BytesIO(response['Body'].read())) return image def resize_image(image): image.thumbnail((100, 100)) # Convert RGBA to RGB if necessary if image.mode == 'RGBA': image = image.convert('RGB') buffer = io.BytesIO() image.save(buffer, 'JPEG') buffer.seek(0) return buffer def save_image_to_s3(image, bucket, key): s3.upload_fileobj(image, bucket, key)