Image Resize Service

JS
S
JavaScript

Lambda function. Code from AWS. https://aws.amazon.com/blogs/compute/resize-images-on-the-fly-with-amazon-s3-aws-lambda-and-amazon-api-gateway/ More robust solution: https://docs.aws.amazon.com/solutions/latest/serverless-image-handler/welcome.html

1'use strict';
2
3const AWS = require('aws-sdk');
4const S3 = new AWS.S3({
5  signatureVersion: 'v4',
6});
7const Sharp = require('sharp');
8
9const BUCKET = process.env.BUCKET;
10const URL = process.env.URL;
11const ALLOWED_RESOLUTIONS = process.env.ALLOWED_RESOLUTIONS ? new Set(process.env.ALLOWED_RESOLUTIONS.split(/\s*,\s*/)) : new Set([]);
12
13exports.handler = function(event, context, callback) {
14  const key = event.queryStringParameters.key;
15  const match = key.match(/((\d+)x(\d+))\/(.*)/);
16
17  //Check if requested resolution is allowed
18  if(0 != ALLOWED_RESOLUTIONS.size && !ALLOWED_RESOLUTIONS.has(match[1]) ) {
19    callback(null, {
20      statusCode: '403',
21      headers: {},
22      body: '',
23    });
24    return;
25  }
26
27  const width = parseInt(match[2], 10);
28  const height = parseInt(match[3], 10);
29  const originalKey = match[4];
30
31  S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
32    .then(data => Sharp(data.Body)
33      .resize(width, height)
34      .toFormat('png')
35      .toBuffer()
36    )
37    .then(buffer => S3.putObject({
38        Body: buffer,
39        Bucket: BUCKET,
40        ContentType: 'image/png',
41        Key: key,
42      }).promise()
43    )
44    .then(() => callback(null, {
45        statusCode: '301',
46        headers: {'location': `${URL}/${key}`},
47        body: '',
48      })
49    )
50    .catch(err => callback(err))
51}
52

Created on 11/13/2018