├── .eslintrc.json ├── LICENSE.md ├── README.md ├── resize-s3-image ├── README.md ├── index.js ├── policy.json └── test-event.json └── transcode-s3-video ├── README.md ├── index.js ├── policy.json └── test-event.json /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint:recommended", 3 | "parserOptions": { 4 | "ecmaVersion": 6, 5 | "sourceType": "module" 6 | }, 7 | "env": { 8 | "node": true 9 | } 10 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | AWS Lambda functions to process videos and resize images. 2 | 3 | See the individual README in each subdirectory for usage info or read my post about [image and video processing for static sites](https://medium.com/@sawyerh/image-and-video-processing-for-your-static-site-66c6dfff5de6) 4 | 5 | ### Author 6 | 7 | [Sawyer Hollenshead](http://www.sawyerh.com/) 8 | 9 | ### License 10 | 11 | [CC0](https://creativecommons.org/publicdomain/zero/1.0/) 12 | -------------------------------------------------------------------------------- /resize-s3-image/README.md: -------------------------------------------------------------------------------- 1 | An AWS Lambda function that's triggered when a new image is added to an S3 bucket and creates resized versions of that image. 2 | 3 | ## Usage 4 | 5 | 1. Set your image versions and output directory in the `CONFIG` object at the top of `index.js`. **Important: You'll likely want to set the output directory (`OUTPUT_PREFIX`) to a different directory than the one your original images are uploaded to, otherwise S3 may send an event notification to Lambda after each resized image is placed in your bucket, and you don't want that.** 6 | 1. [Create a new Lambda function](http://docs.aws.amazon.com/lambda/latest/dg/getting-started.html). Skip the blueprints screen, copy + paste the contents of `index.js` into the inline code editor. Make sure the "Handler" is set to index.handler. Make sure the IAM role you select has the `s3:GetObject` and `s3:PutObject` permissions. (see policy.json) 7 | 1. Set up your S3 bucket to [send events to your Lambda function](http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) when a new image object is created. 8 | 9 | ## Lambda settings 10 | 11 | - **Runtime**: Node.js 4.3 12 | - **Memory**: 512 MB 13 | - **Timeout**: 30 sec. 14 | -------------------------------------------------------------------------------- /resize-s3-image/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const CONFIG = { 3 | // Set the directory where you'd like resized 4 | // images to be placed. This should be different 5 | // than where your original image was uploaded. 6 | // This can also be used to add a prefix to the 7 | // resized file's name: 8 | OUTPUT_PREFIX: 'uploads/', 9 | // Set the sizes your image should be resized to fit 10 | // Add a new object to this array for each version. 11 | // The suffix will be appended to the resized file's name: 12 | VERSIONS: [ 13 | { 14 | maxHeight: 100, 15 | maxWidth: 100, 16 | suffix: 'thumb' 17 | }, { 18 | maxHeight: 300, 19 | maxWidth: 500, 20 | suffix: 'small' 21 | } 22 | ] 23 | }; 24 | 25 | // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 26 | // DO NOT EDIT BELOW THIS LINE UNLESS YOU'RE WISE 27 | // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 28 | var AWS = require('aws-sdk'); 29 | var ImageMagick = require("imagemagick"); 30 | var fs = require('fs'); 31 | var s3 = new AWS.S3(); 32 | 33 | function basename(path) { 34 | return path.split('/').reverse()[0].split('.')[0]; 35 | } 36 | 37 | function extension(path) { 38 | let typeMatch = path.match(/\.([^.]*)$/); 39 | if (!typeMatch) return null; 40 | return typeMatch[1]; 41 | } 42 | 43 | function ImageResizer(bucket, key, callback) { 44 | this.bucket = bucket; 45 | this.key = key; 46 | this.ext = extension(key); 47 | this.callback = callback; 48 | this.s3Object = null; 49 | this.width = null; 50 | this.height = null; 51 | } 52 | 53 | ImageResizer.prototype.resizeAll = function() { 54 | this.download() 55 | .then(this.getDimensions.bind(this)) 56 | .then(this.resize.bind(this)) 57 | .then(() => this.callback(null, `Resized ${this.key}`)) 58 | .catch((error) => this.callback(error)); 59 | }; 60 | 61 | ImageResizer.prototype.resize = function(index) { 62 | if (!index) index = 0; 63 | const version = CONFIG.VERSIONS[index]; 64 | 65 | return this.transformAndUpload(version) 66 | .then(() => { 67 | if (index < CONFIG.VERSIONS.length - 1) 68 | return this.resize(index + 1); 69 | }); 70 | }; 71 | 72 | ImageResizer.prototype.download = function() { 73 | return new Promise((resolve, reject) => { 74 | s3.getObject({ Bucket: this.bucket, Key: this.key }, (error, s3Object) => { 75 | if (error) return reject(error); 76 | this.s3Object = s3Object; 77 | resolve(); 78 | }); 79 | }); 80 | }; 81 | 82 | ImageResizer.prototype.getDimensions = function() { 83 | return new Promise((resolve, reject) => { 84 | const tmpFilePath = `/tmp/inputFile.${this.ext}`; 85 | fs.writeFileSync(tmpFilePath, this.s3Object.Body); 86 | 87 | ImageMagick.identify(['-format', '%wx%h', tmpFilePath], (err, output) => { 88 | fs.unlinkSync(tmpFilePath); 89 | if (err) return reject(err); 90 | 91 | let dimensions = output.trim().split('x'); 92 | this.width = dimensions[0]; 93 | this.height = dimensions[1]; 94 | resolve(); 95 | }); 96 | }); 97 | }; 98 | 99 | ImageResizer.prototype.transformAndUpload = function(version) { 100 | return new Promise((resolve, reject) => { 101 | // Infer the scaling factor to avoid 102 | // stretching the image unnaturally. 103 | const scalingFactor = Math.min( 104 | version.maxWidth / this.width, 105 | version.maxHeight / this.height 106 | ); 107 | 108 | const tmpFilePath = `/tmp/resized.${this.ext}`; 109 | const width = scalingFactor * this.width; 110 | const height = scalingFactor * this.height; 111 | const data = { 112 | srcData: this.s3Object.Body, 113 | dstPath: tmpFilePath, 114 | height: height, 115 | width: width 116 | }; 117 | 118 | try { 119 | ImageMagick.resize(data, (err, stdout, stderr) => { 120 | if (err) return reject(err); 121 | var resizedBuffer = new Buffer(fs.readFileSync(tmpFilePath)); 122 | this.upload(resizedBuffer, version) 123 | .then(() => { 124 | try { fs.unlinkSync(tmpFilePath) } catch (e) {} 125 | resolve(); 126 | }) 127 | .catch(reject); 128 | }); 129 | } catch (err) { 130 | reject(err); 131 | } 132 | }); 133 | }; 134 | 135 | ImageResizer.prototype.upload = function(resizedBuffer, version) { 136 | const filename = basename(this.key) + "_" + version.suffix + "." + this.ext; 137 | 138 | return new Promise((resolve, reject) => { 139 | s3.putObject({ 140 | Bucket: this.bucket, 141 | Key: `${CONFIG.OUTPUT_PREFIX}${filename}`, 142 | Body: resizedBuffer, 143 | ContentType: this.s3Object.ContentType 144 | }, (err) => { 145 | if (err) return reject(err); 146 | resolve(); 147 | }); 148 | }); 149 | }; 150 | 151 | exports.handler = function(event, context, callback) { 152 | console.log('Received event:', JSON.stringify(event, null, 2)); 153 | const bucket = event.Records[0].s3.bucket.name; 154 | const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); 155 | const ext = extension(key); 156 | let resizer = new ImageResizer(bucket, key, callback); 157 | 158 | if (!ext || ['jpg', 'jpeg', 'png'].indexOf(ext) < 0) 159 | return callback(null, "Skipping transformation. File extension is not jpg/jpeg/png: " + key); 160 | 161 | return resizer.resizeAll(); 162 | }; -------------------------------------------------------------------------------- /resize-s3-image/policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "logs:CreateLogGroup", 8 | "logs:CreateLogStream", 9 | "logs:PutLogEvents" 10 | ], 11 | "Resource": "arn:aws:logs:*:*:*" 12 | }, 13 | { 14 | "Effect": "Allow", 15 | "Action": [ 16 | "s3:GetObject", 17 | "s3:PutObject" 18 | ], 19 | "Resource": [ 20 | "arn:aws:s3:::example-bucket/*" 21 | ] 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /resize-s3-image/test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records": [ 3 | { 4 | "s3": { 5 | "bucket": { 6 | "name": "example-bucket", 7 | "arn": "arn:aws:s3:::example-bucket" 8 | }, 9 | "object": { 10 | "key": "uploads/example.jpg" 11 | } 12 | } 13 | } 14 | ] 15 | } 16 | 17 | -------------------------------------------------------------------------------- /transcode-s3-video/README.md: -------------------------------------------------------------------------------- 1 | An AWS Lambda function that's triggered when a new video is added to an S3 bucket and creates transcoded versions of that video using AWS Elastic Transcoder. 2 | 3 | ## Usage 4 | 5 | 1. [Create an Elastic Transcoder Pipeline](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/creating-pipelines.html) 6 | 2. Set your Pipeline ID, presets, and output directory in the `CONFIG` object at the top of `index.js`. 7 | 3. [Create a new Lambda function](http://docs.aws.amazon.com/lambda/latest/dg/getting-started.html). Skip the blueprints screen, copy + paste the contents of `index.js` into the inline code editor. Make sure the "Handler" is set to index.handler. Make sure the IAM role you select has the `elastictranscoder:CreateJob` permission. (see policy.json) 8 | 4. Set up your S3 bucket to [send events to your Lambda function](http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) when a new video object is created. 9 | 10 | ## Lambda settings 11 | 12 | - **Runtime**: Node.js 4.3 13 | - **Memory**: 128 MB 14 | - **Timeout**: 3 sec. 15 | -------------------------------------------------------------------------------- /transcode-s3-video/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const CONFIG = { 3 | // Your AWS Elastic Transcoder Pipeline: 4 | PIPELINE_ID: "", 5 | // Set which presets should be used to transcode 6 | // your video. Add a new object to this array 7 | // for each preset. The suffix will be appended 8 | // to the transcoded file's name and should at least 9 | // contain the expected file extension: 10 | PRESETS: [{ 11 | id: "1351620000001-100070", // "System preset: Web" 12 | suffix: ".mp4" 13 | }], 14 | // Set the directory where you'd like transcoded 15 | // videos to be placed. This can also be used to 16 | // add a prefix to the transcoded file's name: 17 | OUTPUT_KEY_PREFIX: "uploads/" 18 | }; 19 | 20 | // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 21 | // DO NOT EDIT BELOW THIS LINE UNLESS YOU'RE WISE 22 | // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 23 | var aws = require('aws-sdk'); 24 | var elastictranscoder = new aws.ElasticTranscoder(); 25 | 26 | function basename(path) { 27 | return path.split('/').reverse()[0].split('.')[0]; 28 | } 29 | 30 | function outputs(name) { 31 | return CONFIG.PRESETS.map(function(output) { 32 | return { 33 | Key: name + output.suffix, 34 | PresetId: output.id, 35 | ThumbnailPattern: name + "-{count}" 36 | }; 37 | }); 38 | } 39 | 40 | exports.handler = function(event, context, callback) { 41 | console.log('Received event:', JSON.stringify(event, null, 2)); 42 | const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); 43 | let params = { 44 | Input: { 45 | Key: key 46 | }, 47 | PipelineId: CONFIG.PIPELINE_ID, 48 | OutputKeyPrefix: CONFIG.OUTPUT_KEY_PREFIX, 49 | Outputs: outputs(basename(key)) 50 | }; 51 | 52 | elastictranscoder.createJob(params, function(err, data) { 53 | if (err) 54 | return callback(err); 55 | 56 | console.log('Created transcoder job: ', data.Job.Id); 57 | return callback(null, data); 58 | }); 59 | }; -------------------------------------------------------------------------------- /transcode-s3-video/policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "logs:CreateLogGroup", 8 | "logs:CreateLogStream", 9 | "logs:PutLogEvents" 10 | ], 11 | "Resource": "arn:aws:logs:*:*:*" 12 | }, 13 | { 14 | "Action": [ 15 | "elastictranscoder:CreateJob" 16 | ], 17 | "Effect": "Allow", 18 | "Resource": "*" 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /transcode-s3-video/test-event.json: -------------------------------------------------------------------------------- 1 | { 2 | "Records": [ 3 | { 4 | "s3": { 5 | "object": { 6 | "key": "uploads/example.mp4" 7 | } 8 | } 9 | } 10 | ] 11 | } --------------------------------------------------------------------------------