├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── api-template.yaml ├── bin └── deploy ├── deploy └── .gitignore ├── dist └── function.zip ├── etc └── nodesource.gpg.key ├── image-resize.yaml └── lambda ├── index.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | lambda/node_modules 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM amazonlinux 2 | 3 | ADD etc/nodesource.gpg.key /etc 4 | 5 | WORKDIR /tmp 6 | 7 | RUN yum -y install gcc-c++ && \ 8 | rpm --import /etc/nodesource.gpg.key && \ 9 | curl --location --output ns.rpm https://rpm.nodesource.com/pub_6.x/el/7/x86_64/nodejs-6.10.1-1nodesource.el7.centos.x86_64.rpm && \ 10 | rpm --checksig ns.rpm && \ 11 | rpm --install --force ns.rpm && \ 12 | npm install -g npm@latest && \ 13 | npm cache clean --force && \ 14 | yum clean all && \ 15 | rm --force ns.rpm 16 | 17 | WORKDIR /build 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Amazon Web Services 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all image package dist clean 2 | 3 | all: package 4 | 5 | image: 6 | docker build --tag amazonlinux:nodejs . 7 | 8 | package: image 9 | docker run --rm --volume ${PWD}/lambda:/build amazonlinux:nodejs bash -c "yum install -y make && npm install --production" 10 | 11 | dist: package 12 | cd lambda && zip -FS -q -r ../dist/function.zip * 13 | 14 | clean: 15 | rm -r lambda/node_modules 16 | docker rmi --force amazonlinux:nodejs 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Archived 2 | 3 | See https://github.com/awslabs/serverless-image-handler instead. 4 | 5 | # Serverless Image Resizing 6 | 7 | ## Description 8 | 9 | Resizes images on the fly using Amazon S3, AWS Lambda, and Amazon API Gateway. 10 | Using a conventional URL structure and S3 static website hosting with 11 | redirection rules, requests for resized images are redirected to a Lambda 12 | function via API Gateway which will resize the image, upload it to S3, and 13 | redirect the requestor to the resized image. The next request for the resized 14 | image will be served from S3 directly. 15 | 16 | ## Usage 17 | 18 | 1. Build the Lambda function 19 | 20 | The Lambda function uses [sharp][sharp] for image resizing which requires 21 | native extensions. In order to run on Lambda, it must be packaged on Amazon 22 | Linux. You can accomplish this in one of two ways: 23 | 24 | - Upload the contents of the `lambda` subdirectory to an [Amazon EC2 instance 25 | running Amazon Linux][amazon-linux] and run `npm install`, or 26 | 27 | - Use the Amazon Linux Docker container image to build the package using your 28 | local system. This repo includes Makefile that will download Amazon Linux, 29 | install Node.js and developer tools, and build the extensions using Docker. 30 | Run `make all`. 31 | 32 | 2. Deploy the CloudFormation stack 33 | 34 | Run `bin/deploy` to deploy the CloudFormation stack. It will create a 35 | temporary Amazon S3 bucket, package and upload the function, and create the 36 | Lambda function, Amazon API Gateway RestApi, and an S3 bucket for images via 37 | CloudFormation. 38 | 39 | The deployment script requires the [AWS CLI][cli] version 1.11.19 or newer 40 | to be installed. Be sure to [set your AWS credentials][aws-configure] using `aws configure` 41 | 42 | 3. Test the function 43 | 44 | Upload an image to the S3 bucket and try to resize it via your web browser 45 | to different sizes, e.g. with an image uploaded in the bucket called 46 | image.png: 47 | 48 | - http://[BucketWebsiteHost]/300x300/path/to/image.png 49 | - http://[BucketWebsiteHost]/90x90/path/to/image.png 50 | - http://[BucketWebsiteHost]/40x40/path/to/image.png 51 | 52 | You can find the `BucketWebsiteUrl` in the table of outputs displayed on a 53 | successful invocation of the deploy script. 54 | 55 | 4. (Optional) Restrict resize dimensions 56 | 57 | To restrict the dimensions the function will create, set the environment 58 | variable `ALLOWED_DIMENSIONS` to a string in the format 59 | *(HEIGHT)x(WIDTH),(HEIGHT)x(WIDTH),...*. 60 | 61 | For example: *300x300,90x90,40x40*. 62 | 63 | ## License 64 | 65 | This reference architecture sample is [licensed][license] under Apache 2.0. 66 | 67 | [license]: LICENSE 68 | [sharp]: https://github.com/lovell/sharp 69 | [amazon-linux]: https://aws.amazon.com/blogs/compute/nodejs-packages-in-lambda/ 70 | [cli]: https://aws.amazon.com/cli/ 71 | [aws-configure]: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html 72 | -------------------------------------------------------------------------------- /api-template.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | swagger: 2.0 3 | info: 4 | title: ServerlessResizeApi 5 | paths: 6 | /: 7 | get: 8 | x-amazon-apigateway-integration: 9 | uri: arn:aws:apigateway:REGION:lambda:path/2015-03-31/functions/arn:aws:lambda:REGION:ACCOUNT_ID:function:${stageVariables.LambdaFunctionName}/invocations 10 | type: AWS_PROXY 11 | httpMethod: post 12 | -------------------------------------------------------------------------------- /bin/deploy: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o errexit 4 | 5 | stack_name=ServerlessImageResize 6 | region="$(aws configure get region)" 7 | bucket_name="temp-serverless-resize-$(openssl rand -hex 8)" 8 | account_id="$(aws sts get-caller-identity --query Account --output text \ 9 | | xargs echo -n | tr -d '\r')" 10 | 11 | set -o xtrace 12 | 13 | sed -e "s/REGION/${region}/g" -e "s/ACCOUNT_ID/${account_id}/g" \ 14 | api-template.yaml > deploy/api.yaml 15 | 16 | aws s3 mb "s3://${bucket_name}" 17 | 18 | aws cloudformation package \ 19 | --output-template-file=deploy/output.yaml \ 20 | --template-file=image-resize.yaml \ 21 | --s3-bucket="${bucket_name}" \ 22 | 23 | aws cloudformation deploy \ 24 | --template-file=deploy/output.yaml \ 25 | --stack-name="${stack_name}" \ 26 | --capabilities=CAPABILITY_NAMED_IAM 27 | 28 | aws s3 rb --force "s3://${bucket_name}" 29 | 30 | aws cloudformation describe-stacks \ 31 | --stack-name "${stack_name}" \ 32 | --query Stacks[].Outputs \ 33 | --output table 34 | -------------------------------------------------------------------------------- /deploy/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /dist/function.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-archives/serverless-image-resizing/8879a511f82388d49ccd890c46484574772724eb/dist/function.zip -------------------------------------------------------------------------------- /etc/nodesource.gpg.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP PUBLIC KEY BLOCK----- 2 | Version: GnuPG v1 3 | 4 | mQINBFQCN9QBEADv5QYOlCWNkI/oKST/GGpQkOZjFY2cbYdHuc2j8kyM4oeNluXq 5 | puEYMHOoQvbJ3DFPvsv+jCruL7qjkel9YzaF6e3RN2ystP4YBjxyOT7Bb5EnjNNU 6 | 6oScQJ50/+RmA4N3wzBrw5+x5KQGBfRU/k7JdDKO6SGY0zzdAo3jqp1nQ9Sf+Fmg 7 | hsjDLVZTHorLPV3yPLb37QlvBB2YIRF+dL9l4wPAI/fGyWv+Qs7VlCZTyRAnKGbv 8 | qN1LvlYoV9YqxaJYYJW+MQhn4706yNJAFeOZuKejEcnZTd/NBiAR91sVnsXKgW9e 9 | yb4TZ7SqkmrJpuKJBpdPr1dgaK8dDmFh9Nlhpz6xZuYcKaDEDa5b3wymnixtwZf2 10 | WyboChIlsHDajtXZt34xP9uUge1VHyk1o8AQUzKEpuepxxLnyXArLgvHaLhQnxPA 11 | bQB43b4RbWYHPdB16ki2WoZX/DA4YEtfxg8GC3zXC2thMJnFburmts71iiYsxKBc 12 | 6d7O8415xrErhk2/o2+bRhf+7qBQfW0oxQSEMBYbqP3hvhG1VWc9umjbCfMgHrHo 13 | IzI7W+GbRdbSsdpY6JNKuCftVfIKXeXk5FbUUP9NzsG/nyGFORkq9y0AKmocx3TD 14 | w9DRG2SmKIKBOG5PQuzuXqsdUaYcFpySXdPNQG2CPtguPhQivw4qM3pQpQARAQAB 15 | tCNOb2RlU291cmNlIDxncGctcnBtQG5vZGVzb3VyY2UuY29tPokCOAQTAQIAIgUC 16 | VAI31AIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQXdvo1DT6dN2uaA// 17 | UwKsmnz4MCH7Jn/vG0OinGQTfSH5uvlH68yOZmKLnhtfiqUq1gZz734S75ExxGP4 18 | SGFYeK9CqKFgoGbpjzLLc5kvA7GdDX3E/exEjYa+GrJ9uIOUtaCKstTD5fPVj2Wf 19 | TZtK9v1F6iYKyPHdJnSc5p7AxbLZkarF1CPJQWv2iDrg3dO3Oy41aazRwxJe9hvI 20 | a//XavnsW2TTeo8qfQ0qrs8vzt8bxJF+PkACmqQfbXAiflCct5XEUbhbX1b8KznP 21 | ppd5PLrvRTjHnZi/QRjky0qsUOukGiQhT6iZeiOUcLPeD+f7tA7JBZ08XXRfnLLj 22 | mqYbIHPFG4C/AM5RXu5OdCtFrZQsJgGQEeg/UxYEz5qqNljKjRZ8XsmcyeWouKFM 23 | LuVr1ORF6crl8lAdT3RujP2MzY8cvxJQesYKdWqk3bPXI7oG/PRReoeN86TqraYO 24 | UeTssVlw5lmJtAH+eHt3K6TSjd0rq1RY7xWfttD7L8ECfPmBzbL54MSmKx9MBz+o 25 | a9vOWQ2LjIbR/6DEyQiDpGhQTM+r0/SVS/kqR/j0SEHvOql+sn9sK1/qR1h3JtgI 26 | 6YF4IDXBE9s0RBCLbdxtVf3eAcbOnhkhefMtpURJLdVuU8HhMCiVUlHDUPHIuT5z 27 | Lp+avdanIgi8Cnps/DpMI2KigEHW5mmqihXtfKj0jeE= 28 | =9Bql 29 | -----END PGP PUBLIC KEY BLOCK----- 30 | -------------------------------------------------------------------------------- /image-resize.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | 3 | Transform: AWS::Serverless-2016-10-31 4 | 5 | Resources: 6 | Api: 7 | Type: AWS::Serverless::Api 8 | Properties: 9 | DefinitionUri: ./deploy/api.yaml 10 | StageName: prod 11 | Variables: 12 | LambdaFunctionName: !Ref ResizeFunction 13 | 14 | ImageBucket: 15 | Type: AWS::S3::Bucket 16 | DeletionPolicy: Retain 17 | Properties: 18 | AccessControl: PublicRead 19 | WebsiteConfiguration: 20 | IndexDocument: index.html 21 | RoutingRules: 22 | - RedirectRule: 23 | HttpRedirectCode: 307 24 | HostName: !Sub ${Api}.execute-api.${AWS::Region}.amazonaws.com 25 | Protocol: https 26 | ReplaceKeyPrefixWith: prod?key= 27 | RoutingRuleCondition: 28 | HttpErrorCodeReturnedEquals: 404 29 | 30 | ResizeFunction: 31 | Type: AWS::Serverless::Function 32 | Properties: 33 | CodeUri: ./dist/function.zip 34 | Handler: index.handler 35 | Runtime: nodejs6.10 36 | MemorySize: 1536 37 | Timeout: 60 38 | Environment: 39 | Variables: 40 | BUCKET: !Ref ImageBucket 41 | URL: !GetAtt ImageBucket.WebsiteURL 42 | Policies: 43 | Statement: 44 | - Resource: !Sub arn:aws:s3:::${ImageBucket}/* 45 | Effect: Allow 46 | Action: 47 | - s3:PutObject 48 | 49 | ResizeFunctionPermission: 50 | Type: AWS::Lambda::Permission 51 | Properties: 52 | FunctionName: !Ref ResizeFunction 53 | Action: lambda:InvokeFunction 54 | Principal: apigateway.amazonaws.com 55 | SourceArn: !Sub arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${Api}/* 56 | 57 | ImageBucketPolicy: 58 | Type: AWS::S3::BucketPolicy 59 | Properties: 60 | Bucket: !Ref ImageBucket 61 | PolicyDocument: 62 | Statement: 63 | - Action: s3:GetObject 64 | Effect: Allow 65 | Principal: "*" 66 | Resource: !Sub arn:aws:s3:::${ImageBucket}/* 67 | 68 | Outputs: 69 | BucketWebsiteUrl: 70 | Value: !GetAtt ImageBucket.WebsiteURL 71 | Bucket: 72 | Value: !Ref ImageBucket 73 | -------------------------------------------------------------------------------- /lambda/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const AWS = require('aws-sdk'); 4 | const S3 = new AWS.S3({ 5 | signatureVersion: 'v4', 6 | }); 7 | const Sharp = require('sharp'); 8 | 9 | const BUCKET = process.env.BUCKET; 10 | const URL = process.env.URL; 11 | const ALLOWED_DIMENSIONS = new Set(); 12 | 13 | if (process.env.ALLOWED_DIMENSIONS) { 14 | const dimensions = process.env.ALLOWED_DIMENSIONS.split(/\s*,\s*/); 15 | dimensions.forEach((dimension) => ALLOWED_DIMENSIONS.add(dimension)); 16 | } 17 | 18 | exports.handler = function(event, context, callback) { 19 | const key = event.queryStringParameters.key; 20 | const match = key.match(/((\d+)x(\d+))\/(.*)/); 21 | const dimensions = match[1]; 22 | const width = parseInt(match[2], 10); 23 | const height = parseInt(match[3], 10); 24 | const originalKey = match[4]; 25 | 26 | if(ALLOWED_DIMENSIONS.size > 0 && !ALLOWED_DIMENSIONS.has(dimensions)) { 27 | callback(null, { 28 | statusCode: '403', 29 | headers: {}, 30 | body: '', 31 | }); 32 | return; 33 | } 34 | 35 | S3.getObject({Bucket: BUCKET, Key: originalKey}).promise() 36 | .then(data => Sharp(data.Body) 37 | .resize(width, height) 38 | .toFormat('png') 39 | .toBuffer() 40 | ) 41 | .then(buffer => S3.putObject({ 42 | Body: buffer, 43 | Bucket: BUCKET, 44 | ContentType: 'image/png', 45 | Key: key, 46 | }).promise() 47 | ) 48 | .then(() => callback(null, { 49 | statusCode: '301', 50 | headers: {'location': `${URL}/${key}`}, 51 | body: '', 52 | }) 53 | ) 54 | .catch(err => callback(err)) 55 | } 56 | -------------------------------------------------------------------------------- /lambda/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "image-resize", 3 | "version": "1.0.0", 4 | "description": "Serverless image resizing", 5 | "readme": "Serverless image resizing", 6 | "repository": "https://github.com/awslabs/serverless-image-resizing", 7 | "license": "Apache-2.0", 8 | "main": "index.js", 9 | "dependencies": { 10 | "sharp": "^0.17.3" 11 | }, 12 | "devDependencies": { 13 | "aws-sdk": "^2.36.0" 14 | } 15 | } 16 | --------------------------------------------------------------------------------