Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created February 13, 2012 19:42
Show Gist options
  • Save simenbrekken/1819483 to your computer and use it in GitHub Desktop.
Save simenbrekken/1819483 to your computer and use it in GitHub Desktop.
Retrieve entry from database, fetch image, store original to S3 along with two different thumbnails.
Entry.findOne({type: 'photo', photo: null}).done(function(entry) {
var thumbnailSize = entry.authorTypeName == 'Photographer' ? 500 : 250;
var options = uri.parse(entry.photoUrl);
var req = http.get(options, function(res) {
if (res.statusCode != 200) return next(new Error('Could not fetch: ' + entry.photoUrl));
var type = res.headers['content-type'];
var length = res.headers['content-length'];
var extension = mime.extension(type);
var path = settings.s3.path + entry._id + '.' + extension;
var headers = {
'content-type': type,
'content-length': length,
'x-amz-acl': 'public-read'
};
async.parallel([
function(callback) {
s3.putStream(path, res, false, headers, function(err) {
callback(err);
});
},
function(callback) {
var image = gm(res);
image.size({bufferStream: true}, function(err, size) {
if (err) return callback(err);
var factor = Math.max(thumbnailSize / size.width, thumbnailSize / size.height);
var width = Math.ceil(size.width * factor);
var height = Math.ceil(size.height * factor);
var offsetX = Math.round((width - thumbnailSize) / 2);
var offsetY = Math.round((height - thumbnailSize) / 2);
image.scale(width, height, offsetX, offsetY).crop(thumbnailSize, thumbnailSize);
image.noProfile().quality(65);
var storeVariant = function(variant, callback) {
image.stream(function(err, stream) {
if (err) return callback(err);
var buffer = new Buffers();
stream.on('data', buffer.push.bind(buffer));
stream.on('end', function() {
var headers = {
'content-type': type,
'x-amz-acl': 'public-read'
};
s3.putBuffer(path + ':' + variant, buffer.toBuffer(), false, headers, function(err) {
callback(err);
});
});
});
};
storeVariant('thumb', function(err) {
if (err) return callback(err);
image.type('Grayscale');
storeVariant('thumbgs', function(err) {
callback(err);
});
});
});
}
], function(err) {
entry.photo = 'http://' + settings.s3.endpoint + '/' + settings.s3.bucket + path;
Entry.save(entry).done(function() {
console.log('All done.');
console.log(entry);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment