Skip to content

Instantly share code, notes, and snippets.

@mattbasta
Created January 13, 2016 01:23
Show Gist options
  • Save mattbasta/777dd0ef59259652f74a to your computer and use it in GitHub Desktop.
Save mattbasta/777dd0ef59259652f74a to your computer and use it in GitHub Desktop.
Started working on an image resizing script for Lambda, but there's too many weird edge cases for me to finish it.
var fs = require('fs');
var path = require('path');
var aws = require('aws-sdk');
var im = require('imagemagick');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });
var postProcessResource = function(resource, fn) {
var ret = null;
if (resource) {
if (fn) {
ret = fn(resource);
}
try {
fs.unlinkSync(resource);
} catch (err) {
// Ignore
}
}
return ret;
};
var resize = function(event, context) {
if (!event.key) {
var msg = 'Invalid resize request: no "key" field supplied';
console.log(msg);
context.fail(msg);
return;
}
if (!event.height || !event.width ||
event.height % 10 !== 0 || event.height > 512 ||
event.width % 10 !== 0 || event.width > 512) {
context.fail(new Error('Invalid height or width specified'));
}
var params = {
Bucket: 'podmaster-host',
Key: event.key,
};
s3.getObject(params, function(err, data) {
if (err) {
console.log('Error getting object ' + event.key + ' from bucket podmaster-host. ' +
'Make sure they exist and your bucket is in the same region as this function.');
context.fail('Error getting file: ' + err);
return;
}
var resizedFile = '/tmp/resized.png';
try {
im.resize({
dstPath: resizedFile,
format: 'png',
height: event.height,
srcData: data.Body,
strip: true,
width: event.width,
}, function(err, stdout, stderr) {
if (err) {
console.error(stderr);
context.fail(err);
return;
}
console.log('Resize operation completed successfully');
context.succeed(postProcessResource(resizedFile, function(file) {
return new Buffer(fs.readFileSync(file));
}));
});
} catch (err) {
console.log('Resize operation failed:', err);
context.fail(err);
}
});
};
exports.handler = function(event, context) {
if (operation) {
console.log('Operation', event.operation, 'requested');
}
switch (event.operation) {
case 'resize':
resize(event, context);
break;
default:
context.fail(new Error('Unrecognized operation "' + operation + '"'));
}
};
@mattbasta
Copy link
Author

Lambda doesn't let you succeed Buffers directly, so you have to encode the data. Their example base64-encodes the image, which isn't very useful. In theory, you could ASCII encode the image, but then you've got caching headers to worry about so you can put it behind Cloudflare or something sane. It's also probably very inefficient, so I will probably just do this as some sort of extension to pinecast-softmirror.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment