Skip to content

Instantly share code, notes, and snippets.

@ivgomezarnedo
Last active March 23, 2023 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivgomezarnedo/91250b8aaa79875e805de6fbf462237c to your computer and use it in GitHub Desktop.
Save ivgomezarnedo/91250b8aaa79875e805de6fbf462237c to your computer and use it in GitHub Desktop.
Lambda function that generates a thumbnail for any image file uploaded to S3.
import os
import json
import boto3
from PIL import Image
import pathlib
import urllib
# Read from environmental variables
ID = os.environ['AWS_ID']
KEY = os.environ['AWS_KEY']
REGION = os.environ['AWS_REGION']
BUCKET = os.environ['BUCKET_NAME']
def lambda_handler(event, context):
# Init S3 Client
client = boto3.client(
's3',
aws_access_key_id=ID,
aws_secret_access_key=KEY,
region_name=REGION
)
for record in event['Records']:
# Read new file (S3 Event: it will always contain one element). Each new file will generate a new event and a new Lambda will be called.
image_path = record['s3']['object']['key']
# Format string to a path that can be read by Boto3
image_path = urllib.parse.unquote_plus(image_path)
lambda_download_path = f"/tmp/{pathlib.Path(image_path).name}" # Local path to download the new file.
lambda_new_file_path = f"/tmp/{get_new_file_name(image_path)}" # Local path in which to create the new file (thumbnail).
s3_new_file_path = f"thumbnails/{get_new_file_name(image_path)}" # S3 path in which to upload the new file (thumbnail)
# Download new file to Lambda local
client.download_file(BUCKET, image_path, lambda_download_path)
# Read the new file and generate the thumbnail
image = Image.open(lambda_download_path)
MAX_SIZE = (200, 200)
image.thumbnail(MAX_SIZE)
image.save(lambda_new_file_path)
# Upload the thumbnail to S3
client.upload_file(lambda_new_file_path, BUCKET,s3_new_file_path)
print(f'New file uploaded to path {s3_new_file_path}')
return {
'statusCode': 200,
'body': json.dumps(s3_new_file_path)
}
def get_new_file_name(file_name):
# Takes the file passed as parameter and adds the suffix 'thumbnail' before the file format.
file_extension = pathlib.Path(file_name).suffix
file_name = pathlib.Path(file_name).stem
return f"{file_name}_thumbnail{file_extension}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment