• Stars
    star
    824
  • Rank 54,972 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatic image resize/reduce on AWS Lambda

aws-lambda-image

Build Status Code Climate Coverage Status npm version Join the chat at https://gitter.im/aws-lambda-image

An AWS Lambda Function to resize/reduce images automatically. When an image is put on AWS S3 bucket, this package will resize/reduce it and put to S3.

Requirements

  • Node.js ( AWS Lambda supports versions of 8.10 or later )

Important Notice

From nodejs10.x, AWS Lambda doesn't bundle ImageMagick and image related libraries.

https://forums.aws.amazon.com/thread.jspa?messageID=906619&tstart=0

Therefore, if you'd deploy with nodejs10.x runtime (but we prefer and default as it), it needs to install AWS Lambda Layer with this function. This project can support it automatically, see LAYERS in detail.

Preparation

Clone this repository and install dependencies:

git clone [email protected]:ysugimoto/aws-lambda-image.git
cd aws-lambda-image
npm install .

When upload to AWS Lambda, the project will bundle only needed files - no dev dependencies will be included.

Configuration

Configuration file you will find under the name config.json in project root. It's copy of our example file config.json.sample. More or less it looks like:

{
  "bucket": "your-destination-bucket",
  "backup": {
      "directory": "./original"
  },
  "reduce": {
      "directory": "./reduced",
      "prefix": "reduced-",
      "quality": 90,
      "acl": "public-read",
      "cacheControl": "public, max-age=31536000"
  },
  "resizes": [
    {
      "size": 300,
      "directory": "./resized/small",
      "prefix": "resized-",
      "cacheControl": null
    },
    {
      "size": 450,
      "directory": "./resized/medium",
      "suffix": "_medium"
    },
    {
      "size": "600x600^",
      "gravity": "Center",
      "crop": "600x600",
      "directory": "./resized/cropped-to-square"
    },
    {
      "size": 600,
      "directory": "./resized/600-jpeg",
      "format": "jpg",
      "background": "white"
    },
    {
      "size": 900,
      "directory": "./resized/large",
      "quality": 90
    }
  ]
}

Configuration Parameters

name field type description
bucket - String Destination bucket name at S3 to put processed image. If not supplied, it will use same bucket of event source.
jpegOptimizer - String Determine optimiser that should be used mozjpeg (default) or jpegoptim ( only JPG ).
acl - String Permission of S3 object. See AWS ACL documentation.
cacheControl - String Cache-Control of S3 object. If not specified, defaults to original image's Cache-Control.
keepExtension - Boolean Global setting fo keeping original extension. If true, program keeps orignal file extension. otherwise use strict extension eg JPG,jpeg -> jpg
backup - Object Backup original file setting.
bucket String Destination bucket to override. If not supplied, it will use bucket setting.
directory String Image directory path. Supports relative and absolute paths. Mode details in DIRECTORY.md
template Object Map representing pattern substitution pair. Mode details in DIRECTORY.md
prefix String Prepend filename prefix if supplied.
suffix String Append filename suffix if supplied.
acl String Permission of S3 object. See AWS ACL documentation.
cacheControl String Cache-Control of S3 object. If not specified, defaults to original image's Cache-Control.
keepExtension Boolean If true, program keeps orignal file extension. otherwise, use strict extension eg JPG,jpeg -> jpg
move Boolean If true, an original uploaded file will delete from Bucket after completion.
reduce - Object Reduce setting following fields.
quality Number Determine reduced image quality ( only JPG ).
jpegOptimizer String Determine optimiser that should be used mozjpeg (default) or jpegoptim ( only JPG ).
bucket String Destination bucket to override. If not supplied, it will use bucket setting.
directory String Image directory path. Supports relative and absolute paths. Mode details in DIRECTORY.md
template Object Map representing pattern substitution pair. Mode details in DIRECTORY.md
prefix String Prepend filename prefix if supplied.
suffix String Append filename suffix if supplied.
acl String Permission of S3 object. See AWS ACL documentation.
cacheControl String Cache-Control of S3 object. If not specified, defaults to original image's Cache-Control.
keepExtension Boolean If true, program keeps orignal file extension. otherwise, use strict extension eg JPG,jpeg -> jpg
resize - Array Resize setting list of following fields.
size String Image dimensions. See ImageMagick geometry documentation.
format String Image format override. If not supplied, it will leave the image in original format.
crop String Dimensions to crop the image. See ImageMagick crop documentation.
gravity String Changes how size and crop. See ImageMagick gravity documentation.
quality Number Determine reduced image quality ( forces format JPG ).
jpegOptimizer String Determine optimiser that should be used mozjpeg (default) or jpegoptim ( only JPG ).
orientation Boolean Auto orientation if value is true.
bucket String Destination bucket to override. If not supplied, it will use bucket setting.
directory String Image directory path. Supports relative and absolute paths. Mode details in DIRECTORY.md
template Object Map representing pattern substitution pair. Mode details in DIRECTORY.md
prefix String Prepend filename prefix if supplied.
suffix String Append filename suffix if supplied.
acl String Permission of S3 object. See AWS ACL documentation.
cacheControl String Cache-Control of S3 object. If not specified, defaults to original image's Cache-Control.
keepExtension Boolean If true, program keeps orignal file extension. otherwise, use strict extension eg JPG,jpeg -> jpg
optimizers - Object Definitions for override the each Optimizers command arguments.
pngquant Array Pngquant command arguments. Default is ["--speed=1", "256"].
jpegoptim Array Jpegoptim command arguments. Default is ["-s", "--all-progressive"].
mozjpeg Array Mozjpeg command arguments. Default is ["-optimize", "-progressive"].
gifsicle Array Gifsicle command arguments. Default is ["--optimize"].

Note that the optmizers option will force override its command arguments, so if you define these configurations, we don't care any more about how optimizer works.

Testing Configuration

If you want to check how your configuration will work, you can use:

npm run test-config

Installation

Setup

To use the automated deployment scripts you will need to have aws-cli installed and configured.

Deployment scripts are pre-configured to use some default values for the Lambda configuration. I you want to change any of those just use:

npm config set aws-lambda-image:profile default
npm config set aws-lambda-image:region eu-west-1
npm config set aws-lambda-image:memory 1280
npm config set aws-lambda-image:timeout 5
npm config set aws-lambda-image:name lambda-function-name
npm config set aws-lambda-image:role lambda-execution-role

Note that aws-lambda-image:name and aws-lambda-image:role are optional. If you want to change lambda function name or execution role, type above commands before deploy.

And make sure AWS Lambda Layer has installed in your account/region. See LAYERS for instructions.

Deployment

Command below will deploy the Lambda function on AWS, together with setting up roles and policies.

npm run deploy

Notice: Because there are some limitations in Claudia.js support for policies, which could lead to issues with Access Denied when processing images from one bucket and saving them to another, we have decided to introduce support for custom policies.

Custom policies

Policies which should be installed together with our Lambda function are stored in policies/ directory. We keep there policy that grants access to all buckets, which is preventing possible errors with Access Denied described above. If you have any security-related concerns, feel free to change the:

"Resource": [
    "*"
]

in the policies/s3-bucket-full-access.json to something more restrictive, like:

"Resource": [
    "arn:aws:s3:::destination-bucket-name/*"
]

Just keep in mind, that you need to make those changes before you do the deployment.

Adding S3 event handlers

To complete installation process you will need to take one more action. It will allow you to install S3 Bucket event handler, which will send information about all uploaded images directly to your Lambda function.

npm run add-s3-handler --s3_bucket="your-bucket-name" --s3_prefix="directory/" --s3_suffix=".jpg"

You are able to install multiple handlers per Bucket. So, to add handler for PNG files you just need to re-run above command with different suffix, ie:

npm run add-s3-handler --s3_bucket="your-bucket-name" --s3_prefix="directory/" --s3_suffix=".png"

Adding SNS message handlers

As an addition, you can also setup and SNS message handler in case you would like to process S3 events over an SNS topic.

npm run add-sns-handler --sns_topic="arn:of:SNS:topic"

Updating

To update Lambda with you latest code just use command below. Script will build new package and automatically publish it on AWS.

npm run update

More

For more scripts look into package.json.

Complete / Failed hooks

You can handle resize/reduce/backup process on success/error result on index.js. ImageProcessor::run will return Promise object, run your original code:

processor.run(config)
.then(function(proceedImages)) {

    // Success case:
    // proceedImages is list of ImageData instance on you configuration

    /* your code here */

    // notify lambda
    context.succeed("OK, numbers of " + proceedImages.length + " images has proceeded.");
})
.catch(function(messages) {

    // Failed case:
    // messages is list of string on error messages

    /* your code here */

    // notify lambda
    context.fail("Woops, image process failed: " + messages);
});

Image resize

  • ImageMagick (installed on AWS Lambda)

Image reduce

License

MIT License.

Author

Yoshiaki Sugimoto

Image credits

Thanks for testing fixture images:

More Repositories

1

grpc-graphql-gateway

A protoc plugin that generates graphql execution code from Protocol Buffers.
Go
368
star
2

webassembly-lua

Write and compile WebAssembly code with Lua
Python
119
star
3

falco

falco is a VCL parser and linter optimized for Fastly
Go
99
star
4

lua-resty-grpc-gateway

REST <-> gRPC gateway library implementation with OpenResty
Lua
85
star
5

RTCPeerConnectionSample

WebRTC peer connection video chat sample ( chrome only )
JavaScript
31
star
6

resumify

Capture screenshot and make PDF on your HTML presentation.
JavaScript
28
star
7

gssp

GSSP : Golang Style Sheet Postprocessor
Go
24
star
8

vintage

VCL Transpiler for Edge Runtime
Go
20
star
9

ginger

Serverless framework for Go runtime.
Go
16
star
10

markdown-tree-parser

Parse markdown string to Abstract Syntax Tree which we defined.
JavaScript
13
star
11

jest-preset-fastly-js-compute

Jest preset for Fastly Compute@Edge
TypeScript
11
star
12

ls3

AWS S3 file explorer on CLI
Go
11
star
13

cloudflare-worker-lambda-gateway

Example for call lambda function gateway via cloudflare worker
JavaScript
11
star
14

graphql-edge

Execute graphql on the edge
TypeScript
10
star
15

GifManipulator

Treats Animated GIF (GIF89a + Netscape Extension) on PHP-GD
PHP
10
star
16

gqtt

MQTT5 implementation by golang
Go
10
star
17

Terrier

A simple mailform written by PHP
PHP
9
star
18

js-dependency-visualizer

JavaScript Module dependency visualizer
JavaScript
9
star
19

go-kakasi

C binding library of kakasi.
Go
8
star
20

Retriever

A simple / lightweight JavaScript template engine
JavaScript
8
star
21

cloudflare-workers-github-auth

Edge-side GitHub authentication
TypeScript
8
star
22

node-memcached-client

Memcached client library for nodejs with ES6 promisified methods
JavaScript
8
star
23

metro

Windows8 metro UI on brwoser
JavaScript
7
star
24

doorkeeper

Validate Github PullRequest title and description and collect release notes.
Go
6
star
25

like-a-pinboard

Pinboard implementation for myself
JavaScript
6
star
26

go-static-server

Golang local static server for development
Go
6
star
27

grunt-sprockets

Resolve static files like rails
JavaScript
6
star
28

tailor

A tail output on any interface
JavaScript
6
star
29

ScrollBarView

Attach ScrollBar-Node for cocos2d-x's ScrollView/TableView
C++
6
star
30

gqb

Query Builder for Golang
Go
5
star
31

google-meet-api

Yet another Google Meet URL generation API
Go
5
star
32

szfw

Seezoo-Framework
PHP
5
star
33

unifee

Unify static assets into single resource
TypeScript
5
star
34

socket.io-cpp

Socket.IO Client for C++ ( use for cocos2d-x )
C
4
star
35

nw-alfred

Alfred clone on node-webkit
JavaScript
4
star
36

gang

Command tool snippet manager written by Golang
Go
4
star
37

ChatworkNotificationSelector

Enable to Select your chat desktop notification
JavaScript
4
star
38

qrterm

Read QR code from screencapture and process it
Go
3
star
39

twist

Cascade and integrate config struct from various setting files and environment.
Go
3
star
40

lua-local-resolver

Create resolver table from local hosts file
Lua
3
star
41

WebRTetris

Network play "Tetris" using WebRTC-DataChannel API
JavaScript
3
star
42

TFCRatioConverter

Convert multiple ratio published from Toolkit for CreateJS source
JavaScript
3
star
43

robots-linter

Parse and lint robots.txt
TypeScript
3
star
44

KickStart-Lite

Kickstart lightweight version of the template set by the independent jQuery
JavaScript
2
star
45

signalingo

A general signaling server for WebRTC or others
Go
2
star
46

artisan-findup

Call laravel's command-tool "artisan" at any project directory
Makefile
2
star
47

DDUploader

FileUpload with HTML5 Drap And Drop API
JavaScript
2
star
48

ChatworkAPIDriver

Library to simplify the acquisition of data and communication with the Chatwork API.
PHP
2
star
49

openfresh-api

[unofficial] openfresh API client
JavaScript
2
star
50

WebGL-Study

JavaScript
2
star
51

tfapprove

Go
2
star
52

gov

Golang versioning tool
Go
2
star
53

aun

Simple WebSocket Implementation over TCP/TLS.
Go
2
star
54

pss

PHP-CSS-Preprocessor on console/web interface
PHP
2
star
55

Spicy

Spicy is tuned Spyc Yaml Parser
PHP
2
star
56

server-timing-benchmark

Benchmark based on Server Timing API.
JavaScript
1
star
57

tf

Transfer.sh (https://transfer.sh/) utility tool written by Go
Go
1
star
58

seezoo2

JavaScript
1
star
59

esanuka

esanuka is managing idempotency tool for AWS API Gateway.
JavaScript
1
star
60

sssh

Execute SSH to selected host from .ssh/config
Go
1
star
61

jsonenv

Extract JSON-formatted environment value
Go
1
star
62

grunt-node-webkit-builder

node-webkit builder for grunt task
JavaScript
1
star
63

perooon

Example application by seezoo-framework
PHP
1
star
64

account-env-label-chrome-extension

Chrome extension to display environment label in AWS console from your config
JavaScript
1
star
65

pecolify

Transform your golang's data to peco
Go
1
star
66

mqtt-example

MQTT Sample Broker/Publisher/Subscriber implements
Go
1
star
67

kennel

My own project useful JavaScript toolkit.
JavaScript
1
star
68

go-cliargs

CLI argument parser/ manager for golang
Go
1
star
69

workers-template-zig

Template to run zig code on Cloudflare Workers
JavaScript
1
star
70

vite-plugin-fastly-js-compute

Vite plugin for Fastly Compute
TypeScript
1
star
71

fastly-costs

Calculate Fastly service costs includes Compute and VCL.
TypeScript
1
star
72

flint

Back compatible fullstack javascript framework
JavaScript
1
star