Skip to content

Commit

Permalink
renamed image resizing patterns to be more clear
Browse files Browse the repository at this point in the history
  • Loading branch information
seshubaws committed Oct 21, 2024
1 parent 63a7ca7 commit 5587b8e
Show file tree
Hide file tree
Showing 17 changed files with 1,041 additions and 0 deletions.
402 changes: 402 additions & 0 deletions s3-lambda-resizing-dotnet/.gitignore

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions s3-lambda-resizing-dotnet/ImageResize.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.6.33815.320
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImageResize", "ImageResize\ImageResize.csproj", "{FADD6CE5-EDF7-4BFE-B8F5-E84CD788D6DE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FADD6CE5-EDF7-4BFE-B8F5-E84CD788D6DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FADD6CE5-EDF7-4BFE-B8F5-E84CD788D6DE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FADD6CE5-EDF7-4BFE-B8F5-E84CD788D6DE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FADD6CE5-EDF7-4BFE-B8F5-E84CD788D6DE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3B666636-4024-4B31-80A6-CB25C208D7F9}
EndGlobalSection
EndGlobal
128 changes: 128 additions & 0 deletions s3-lambda-resizing-dotnet/ImageResize/Function.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.PixelFormats;
using Amazon.S3.Model;
using SixLabors.ImageSharp.Formats.Jpeg;
using Amazon.Lambda.Core;
using Amazon.Lambda.S3Events;
using Amazon.S3;
using Amazon.S3.Util;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace ImageResize;

public class Function
{
IAmazonS3 S3Client { get; set; }


/// <summary>
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
/// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
/// region the Lambda function is executed in.
/// </summary>
public Function()
{
S3Client = new AmazonS3Client();
}

/// <summary>
/// Constructs an instance with a preconfigured S3 client. This can be used for testing outside of the Lambda environment.
/// </summary>
/// <param name="s3Client"></param>
public Function(IAmazonS3 s3Client)
{
this.S3Client = s3Client;
}

public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
{
string[] fileExtensions = new string[] { ".jpg", ".jpeg" };
var s3Event = evnt.Records?[0].S3;
if (s3Event == null)
{
return null;
}

try
{
foreach (var record in evnt.Records)
{
LambdaLogger.Log("----> File: " + record.S3.Object.Key);
if (!fileExtensions.Contains(Path.GetExtension(record.S3.Object.Key).ToLower()))
{
LambdaLogger.Log("File Extension is not supported - " + s3Event.Object.Key);
continue;
}

string suffix = Path.GetExtension(record.S3.Object.Key).ToLower();
Stream imageStream = new MemoryStream();
using (var objectResponse = await S3Client.GetObjectAsync(record.S3.Bucket.Name, record.S3.Object.Key))
{
using (Stream responseStream = objectResponse.ResponseStream)
{
using (var image = Image.Load(responseStream))
{
// Create B&W thumbnail
image.Mutate(ctx => ctx.Grayscale().Resize(200, 200));
image.Save(imageStream, new JpegEncoder());
imageStream.Seek(0, SeekOrigin.Begin);
}
}
}

// Creating a new S3 ObjectKey for the thumbnails
string thumbnailObjectKey = null;
int endSlash = record.S3.Object.Key.ToLower().LastIndexOf("/");
if (endSlash > 0)
{
string S3ObjectName = record.S3.Object.Key.ToLower().Substring(endSlash + 1);
int beginSlash = 0;
if (endSlash > 0)
{
beginSlash = record.S3.Object.Key.ToLower().Substring(0, endSlash - 1).LastIndexOf("/");
if (beginSlash > 0)
{
thumbnailObjectKey =
record.S3.Object.Key.ToLower().Substring(0, beginSlash) +
"thumbnails/" +
S3ObjectName;
}
else
{
thumbnailObjectKey = "thumbnails/" + S3ObjectName;
}
}
}
else
{
thumbnailObjectKey = "thumbnails/" + record.S3.Object.Key.ToLower();
}

LambdaLogger.Log("----> Thumbnail file Key: " + thumbnailObjectKey);
var destinationBucket = Environment.GetEnvironmentVariable("DESTINATION_BUCKET_NAME");
await S3Client.PutObjectAsync(new PutObjectRequest
{
BucketName = destinationBucket,
Key = thumbnailObjectKey,
InputStream = imageStream
});
}

LambdaLogger.Log("Processed " + evnt.Records.Count.ToString());

return null;
}
catch (Exception e)
{
context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}");
context.Logger.LogLine($"Make sure they exist and your bucket is in the same region as this function");
context.Logger.LogLine(e.Message);
context.Logger.LogLine(e.StackTrace);
throw;
}
}
}
20 changes: 20 additions & 0 deletions s3-lambda-resizing-dotnet/ImageResize/ImageResize.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AWSProjectType>Lambda</AWSProjectType>
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<!-- Generate ready to run images during publishing to improve cold start time. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" />
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.3.1" />
<PackageReference Include="Amazon.Lambda.S3Events" Version="3.0.0" />
<PackageReference Include="AWSSDK.S3" Version="3.7.104.2" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"Mock Lambda Test Tool": {
"commandName": "Executable",
"commandLineArgs": "--port 5050",
"workingDirectory": ".\\bin\\$(Configuration)\\net6.0",
"executablePath": "%USERPROFILE%\\.dotnet\\tools\\dotnet-lambda-test-tool-6.0.exe"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

{
"Information" : [
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
"To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
"dotnet lambda help",
"All the command line options for the Lambda command can be specified in this file."
],
"profile" : "default",
"region" : "us-east-1",
"configuration" : "Release",
"function-runtime" : "dotnet6",
"function-memory-size" : 256,
"function-timeout" : 30,
"function-handler" : "ImageResize::ImageResize.Function::FunctionHandler",
"framework" : "net6.0",
"function-name" : "ImageResize",
"package-type" : "Zip",
"function-role" : "arn:aws:iam::595982400875:role/ImageResizeLambdaRole",
"function-architecture" : "x86_64",
"function-subnets" : "",
"function-security-groups" : "",
"tracing-mode" : "PassThrough",
"environment-variables" : "",
"image-tag" : ""
}
77 changes: 77 additions & 0 deletions s3-lambda-resizing-dotnet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# AWS Amazon S3 to AWS Lambda - Create a Lambda function that resizes images uploaded to S3

The SAM template deploys a .NET 6 Lambda function, an S3 bucket and the IAM resources required to run the application. A Lambda function consumes <code>ObjectCreated</code> events from an Amazon S3 bucket. The function code checks the uploaded file is an image and creates a thumbnail version of the image in the same bucket.

Learn more about this pattern at Serverless Land Patterns: [https://serverlessland.com/patterns/s3-lambda-dotnet](https://serverlessland.com/patterns/s3-lambda-dotnet)

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
* [.Net 6.0](https://dotnet.microsoft.com/en-us/download/dotnet/6.0)
* [Docker](https://docs.docker.com/get-docker/) installed and running

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
1. Change directory to the pattern directory:
```
cd s3-lambda-dotnet
```
1. From the command line, use AWS SAM to build and deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam build
sam deploy --guided
```
1. During the prompts:
* Enter a stack name
* Enter the desired AWS Region
* Allow SAM CLI to create IAM roles with the required permissions.
Once you have run `sam deploy -guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.
1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.
## How it works
* Use the AWS CLI upload an image to S3
* If the object is a .jpeg in the source bucket, the code creates a thumbnail and saves it to the destination bucket in a new folder, /thumbnails.
* The code assumes that the destination bucket exists and is defined in the `template.yaml` file
==============================================
## Testing
Run the following S3 CLI command to upload an image to the S3 bucket. Note, you must edit the {SourceBucketName} placeholder with the name of the S3 Bucket. This is provided in the stack outputs.
```bash
aws s3 cp './images/example.jpeg' s3://{BucketName}/example.jpeg
```

Run the following command to check that a new thumbnails folder has been created with a new version of the image.

```bash
aws s3 ls s3://{BucketName}/thumbnails
```

## Cleanup

1. Delete the stack
```bash
aws cloudformation delete-stack --stack-name STACK_NAME
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
```
----
Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
38 changes: 38 additions & 0 deletions s3-lambda-resizing-dotnet/event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"Records": [
{
"eventVersion": "2.1",
"eventSource": "aws:s3",
"awsRegion": "us-east-1",
"eventTime": "2024-07-03T19:37:27.192Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:AIDAINPONIXQXHT3IKHL2"
},
"requestParameters": {
"sourceIPAddress": "205.255.255.255"
},
"responseElements": {
"x-amz-request-id": "D82B88E5F771F645",
"x-amz-id-2": "vlR7PnpV2Ce81l0PRw6jlUpck7Jo5ZsQjryTjKlc5aLWGVHPZLj5NeC6qMa0emYBDXOo6QBU0Wo="
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "828aa6fc-f7b5-4305-8584-487c791949c1",
"bucket": {
"name": "<provide-source-bucket-name-here>",
"ownerIdentity": {
"principalId": "A3I5XTEXAMAI3E"
},
"arn": "arn:aws:s3:::lambda-artifacts-deafc19498e3f2df"
},
"object": {
"key": "<provide-object-key-here>",
"size": 1305107,
"eTag": "b21b84d653bb07b05b1e6b33684dc11b",
"sequencer": "0C0F6F405D6ED209E1"
}
}
}
]
}
Binary file added s3-lambda-resizing-dotnet/images/example.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 5587b8e

Please sign in to comment.