Created
May 18, 2012 17:46
-
-
Save scttnlsn/2726685 to your computer and use it in GitHub Desktop.
Serving thumbnails on-the-fly with Nettle and Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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