Skip to content

Instantly share code, notes, and snippets.

@ciberch
Created September 5, 2012 22:59
Show Gist options
  • Save ciberch/3646977 to your computer and use it in GitHub Desktop.
Save ciberch/3646977 to your computer and use it in GitHub Desktop.
Using ImageMagick to get photo Metadata with Node.js
var im = require('imagemagick');
var Guid = require('guid');
var siteConf = require('./lib/getConfig');
var lib = new require('./lib/asms-client.js')(app, cf).streamLib;
function ingestPhoto(req, res, next){
if (req.files.image) {
im.identify(req.files.image.path, function(err, features){
if (features && features.width) {
var guid = Guid.create();
// Concatenating name to guid guarantees that we always have
// unique file names
var fileId = guid + '/' + req.files.image.name;
// The GridStore class is the equivalent of a File class but has the
// added benefit of allowing you to store metadata
var gs = lib.GridStore(lib.realMongoDB, fileId, "w", {
content_type : req.files.image.type,
// metadata is optional
metadata : {
author: req.session.user._id,
public : false,
filename: req.files.image.name,
path: req.files.image.path,
width: features.width,
height: features.height,
format: features.format,
size_kb: req.files.image.size / 1024 | 0
}
});
// This command copies the file from the file system(temp dir)
// to GridFS.
// GridFS supports any file size by breaking it into chunks
// behind the scenes
gs.writeFile(req.files.image.path, function(err, doc){
if (err) {
next(err);
} else {
if (! req.photosUploaded) {
req.photosUploaded = {};
}
// I have another express route to serve the photos by fileId
var url = siteConf.uri + "/photos/" + fileId;
// Add the results of the upload to the chain
req.photosUploaded['original'] = {url : url, metadata: gs.metadata};
req.nextSizeIndex = 0;
next();
}
});
} else {
if (err) throw err;
throw(new Error("Cannot get width for photo"));
}
});
} else {
next(new Error("Could not find the file"));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment