├── .gitignore ├── requirements.txt ├── README.md └── app.py /.gitignore: -------------------------------------------------------------------------------- 1 | .chalice 2 | .idea 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.3.1 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Sample code for the AWS Lambda blog posts: https://www.mschweighauser.com/create-a-thumbnail-api-service/ 2 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import uuid 3 | from subprocess import Popen, PIPE 4 | 5 | import boto3 6 | from chalice import BadRequestError, Chalice 7 | 8 | 9 | app = Chalice(app_name='thumbnail-service') 10 | app.debug = True # TODO: Disable on production 11 | 12 | S3 = boto3.client('s3') 13 | S3_BUCKET = '' # TODO: Replace with valid bucket name 14 | 15 | 16 | @app.route('/', methods=['POST']) 17 | def index(): 18 | body = app.current_request.json_body 19 | 20 | image = base64.b64decode(body['data']) 21 | format = {'jpg': 'jpeg', 'png': 'png'}[body.get('format', 'jpg').lower()] 22 | mode = {'max': '', 'min': '^', 'exact': '!'}[body.get('mode', 'max').lower()] 23 | width = int(body.get('width', 128)) 24 | height = int(body.get('height', 128)) 25 | 26 | cmd = [ 27 | 'convert', # ImageMagick Convert 28 | '-', # Read original picture from StdIn 29 | '-auto-orient', # Detect picture orientation from metadata 30 | '-thumbnail', '{}x{}{}'.format(width, height, mode), # Thumbnail size 31 | '-extent', '{}x{}'.format(width, height), # Fill if original picture is smaller than thumbnail 32 | '-gravity', 'Center', # Extend (fill) from the thumbnail middle 33 | '-unsharp',' 0x.5', # Un-sharpen slightly to improve small thumbnails 34 | '-quality', '80%', # Thumbnail JPG quality 35 | '{}:-'.format(format), # Write thumbnail with `format` to StdOut 36 | ] 37 | 38 | p = Popen(cmd, stdout=PIPE, stdin=PIPE) 39 | thumbnail = p.communicate(input=image)[0] 40 | 41 | if not thumbnail: 42 | raise BadRequestError('Image format not supported') 43 | 44 | filename = '{}_{}x{}.{}'.format(uuid.uuid4(), width, height, format) 45 | S3.put_object( 46 | Bucket=S3_BUCKET, 47 | Key=filename, 48 | Body=thumbnail, 49 | ACL='public-read', 50 | ContentType='image/{}'.format(format), 51 | ) 52 | 53 | return { 54 | 'url': 'https://s3.amazonaws.com/{}/{}'.format(S3_BUCKET, filename) 55 | } 56 | --------------------------------------------------------------------------------