Skip to content

Instantly share code, notes, and snippets.

@dariusc93
Created January 2, 2014 18:11
Show Gist options
  • Save dariusc93/8223559 to your computer and use it in GitHub Desktop.
Save dariusc93/8223559 to your computer and use it in GitHub Desktop.
Example of image resizing
module.exports = {
index: function(req,res){
var name = req.params.name;
var sub = name.split('.'),fname = sub[sub.length-2],ext = sub[sub.length-1];
var imgpath = __dirname+'/../../assets/img/'+fname+'.'+ext;
require('fs').exists(imgpath, function(exist){
if(exist){
var Canvas = require('canvas'),
Image = Canvas.Image,
img = new Image;
img.onerror = function(err){
throw err;
};
img.onload = function(){
var width = parseInt(req.params.x);
var height = parseInt(req.params.y);
if(width > 2048){
width = 2048;
}
if(height > 2048){
height = 2048;
}
var canvas = new Canvas(width, height);
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBuffer(function(err,buf){
if(err){
console.log(err);
res.status(500);
res.end();
}else{
res.status(200);
res.end(buf,'binary');
}
});
};
img.src = imgpath;
}else{
res.status(404);
res.end();
}
});
},
_config: {}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment