Created
September 6, 2012 16:46
-
-
Save ciberch/3658388 to your computer and use it in GitHub Desktop.
Resize photos using Imagemagick and Node.js
This file contains hidden or 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 im = require('imagemagick'); | |
| var Guid = require('guid'); | |
| function reducePhoto(req, res, next){ | |
| var photoIngested = req.photosUploaded['original']; | |
| if (photoIngested) { | |
| var sizeName = sizes[req.nextSizeIndex].name; | |
| var destPath = photoIngested.metadata.path + '-' + sizeName ; | |
| var nameParts = photoIngested.metadata.filename.split('.'); | |
| var newName = nameParts[0] + '-' + sizeName + '.' + nameParts[1]; | |
| var width = sizes[req.nextSizeIndex].width; | |
| im.resize({ | |
| srcPath: photoIngested.metadata.path, | |
| dstPath: destPath, | |
| width: width | |
| }, function(err, stdout, stderr){ | |
| if (err) { | |
| next(err); | |
| } else { | |
| console.log("The photo was resized to " + width + "px wide"); | |
| var guid = Guid.create(); | |
| var fileId = guid + '/' + newName; | |
| var ratio = photoIngested.metadata.width / width; | |
| var height = photoIngested.metadata.height / ratio; | |
| var gs = asmsClient.streamLib.GridStore(asmsClient.streamLib.realMongoDB, fileId, "w", { | |
| content_type : req.files.image.type, | |
| metadata : { | |
| author: req.session.user._id, | |
| public : false, | |
| filename: newName, | |
| width: width, | |
| height: height, | |
| path: destPath | |
| } | |
| }); | |
| gs.writeFile(destPath, function(err, doc){ | |
| if (err) { | |
| next(err); | |
| } else { | |
| var url = siteConf.uri + "/photos/" + fileId; | |
| req.photosUploaded[sizeName] = {url : url, metadata: gs.metadata}; | |
| req.nextSizeIndex = req.nextSizeIndex + 1; | |
| next(); | |
| } | |
| }); | |
| } | |
| }); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment