Take a look at the node node-imagemagick module . An example is given on the module page to resize and image and write it to a file ...
var fs = require('fs'); im.resize({ srcData: fs.readFileSync('kittens.jpg', 'binary'), width: 256 }, function(err, stdout, stderr){ if (err) throw err fs.writeFileSync('kittens-resized.jpg', stdout, 'binary'); console.log('resized kittens.jpg to fit within 256x256px') });
You can change this code to do the following ...
var mime = require('mime') // Get mime type based on file extension. use "npm install mime" , fs = require('fs') , util = require('util') , http = require('http') , im = require('imagemagick'); http.createServer(function (req, res) { var filePath = 'test.jpg'; fs.stat(filePath, function (err, stat) { if (err) { throw err; } fs.readFile(filePath, 'binary', function (err, data) { if (err) { throw err; } im.resize({ srcData: data, width: 256 }, function (err, stdout, stderr) { if (err) { throw err; } res.writeHead(200, { 'Content-Type': mime.lookup(filePath), 'Content-Length': stat.size }); var readStream = fs.createReadStream(filePath); return util.pump(readStream, res); }); }); }); }).listen(8080);
Ps. Not yet run the code. Let's try to do this soon, but it should give you an idea of how to resize and stream the file asynchronously.
source share