Skip to content

Instantly share code, notes, and snippets.

@scttnlsn
Created May 18, 2012 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scttnlsn/2726685 to your computer and use it in GitHub Desktop.
Save scttnlsn/2726685 to your computer and use it in GitHub Desktop.
Serving thumbnails on-the-fly with Nettle and Express
var express = require('express');
var im = require('imagemagick');
var nettle = require('nettle');
var app = express.createServer();
var store = nettle.store({ url: 'mongodb://localhost:27017/mydb' });
// Create Nettle processor to resize image
var createProcessor = function(width) {
store.processor(width, function(buffer, callback) {
var params = {
srcData: buffer.toString('binary'),
width: parseInt(width, 10)
};
im.resize(params, function(err, stdout, stderr) {
if (err) return callback(err);
if (stderr) return callback(new Error(stderr));
callback(null, new Buffer(stdout, 'binary'));
});
});
};
// Serve thumbnail
app.get('/images/:image/thumbnails/:width', function(req, res, next) {
createProcessor(req.params.width);
store.get(req.params.image, req.params.width, function(err, buffer) {
if (err) return next(err);
res.end(buffer, 'binary');
});
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment