Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

using -format for identify to get more robust results #35

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
175 changes: 43 additions & 132 deletions imagemagick.js
@@ -1,139 +1,48 @@
var childproc = require('child_process'), var spawn = require('child_process').spawn,
EventEmitter = require('events').EventEmitter; EventEmitter = require('events').EventEmitter,

StringDecoder = require('string_decoder').StringDecoder;


function exec2(file, args /*, options, callback */) { // based on https://github.com/bahamas10/node-exec
var options = { encoding: 'utf8' function exec2(program, args, opts, callback) {
, timeout: 0 var out = '',
, maxBuffer: 500*1024 err = '',
, killSignal: 'SIGKILL' code,
, output: null i = 0,
}; decoder = new StringDecoder(),

v = process.version.split('.'),
var callback = arguments[arguments.length-1]; version_major = v[0],
if ('function' != typeof callback) callback = null; version_minor = v[1];


if (typeof arguments[2] == 'object') { if (typeof opts === 'function') {
var keys = Object.keys(options); callback = opts;
for (var i = 0; i < keys.length; i++) { opts = null;
var k = keys[i];
if (arguments[2][k] !== undefined) options[k] = arguments[2][k];
}
}

var child = childproc.spawn(file, args);
var killed = false;
var timedOut = false;

var Wrapper = function(proc) {
this.proc = proc;
this.stderr = new Accumulator();
proc.emitter = new EventEmitter();
proc.on = proc.emitter.on.bind(proc.emitter);
this.out = proc.emitter.emit.bind(proc.emitter, 'data');
this.err = this.stderr.out.bind(this.stderr);
this.errCurrent = this.stderr.current.bind(this.stderr);
};
Wrapper.prototype.finish = function(err) {
this.proc.emitter.emit('end', err, this.errCurrent());
};

var Accumulator = function(cb) {
this.stdout = {contents: ""};
this.stderr = {contents: ""};
this.callback = cb;

var limitedWrite = function(stream) {
return function(chunk) {
stream.contents += chunk;
if (!killed && stream.contents.length > options.maxBuffer) {
child.kill(options.killSignal);
killed = true;
}
};
};
this.out = limitedWrite(this.stdout);
this.err = limitedWrite(this.stderr);
};
Accumulator.prototype.current = function() { return this.stdout.contents; };
Accumulator.prototype.errCurrent = function() { return this.stderr.contents; };
Accumulator.prototype.finish = function(err) { this.callback(err, this.stdout.contents, this.stderr.contents); };

var std = callback ? new Accumulator(callback) : new Wrapper(child);

var timeoutId;
if (options.timeout > 0) {
timeoutId = setTimeout(function () {
if (!killed) {
child.kill(options.killSignal);
timedOut = true;
killed = true;
timeoutId = null;
}
}, options.timeout);
} }
var child = spawn(program, args, opts);


child.stdout.setEncoding(options.encoding); child.stdout.on('data', function(data) {
child.stderr.setEncoding(options.encoding); out += decoder.write(data);
});
child.stderr.on('data', function(data) {
err += decoder.write(data);
});


child.stdout.addListener("data", function (chunk) { std.out(chunk, options.encoding); }); child.on('exit', function(c) {
child.stderr.addListener("data", function (chunk) { std.err(chunk, options.encoding); }); code = c;
if (++i >= 2 || (version_major === 0 && version_minor < 8)) callback(err, out, code);
});


child.addListener("exit", function (code, signal) { child.on('close', function() {
if (timeoutId) clearTimeout(timeoutId); if (++i >= 2) callback(err, out, code);
if (code === 0 && signal === null) {
std.finish(null);
} else {
var e = new Error("Command "+(timedOut ? "timed out" : "failed")+": " + std.errCurrent());
e.timedOut = timedOut;
e.killed = killed;
e.code = code;
e.signal = signal;
std.finish(e);
}
}); });


return child; return child;
}; };



// see http://www.imagemagick.org/script/escape.php for formatting options
function parseIdentify(input) {
var lines = input.split("\n"),
prop = {},
props = [prop],
prevIndent = 0,
indents = [indent],
currentLine, comps, indent;

lines.shift(); //drop first line (Image: name.jpg)

for (i in lines) {
currentLine = lines[i];
if (currentLine.length > 0) {
indent = currentLine.search(/\S/);
comps = currentLine.split(': ');
if (indent > prevIndent) indents.push(indent);
while (indent < prevIndent) {
indents.pop();
prop = props.pop();
prevIndent = indents[indents.length - 1];
}
if (comps.length < 2) {
props.push(prop);
prop = prop[currentLine.split(':')[0].trim().toLowerCase()] = {};
} else {
prop[comps[0].trim().toLowerCase()] = comps[1].trim()
}
prevIndent = indent;
}
}
return props[0];
};

exports.identify = function(pathOrArgs, callback) { exports.identify = function(pathOrArgs, callback) {
var isCustom = Array.isArray(pathOrArgs), var isCustom = Array.isArray(pathOrArgs),
isData, isData,
args = isCustom ? ([]).concat(pathOrArgs) : ['-verbose', pathOrArgs]; args = isCustom ? ([]).concat(pathOrArgs) : ['-format', '%m %w %h %z %Q', pathOrArgs];


if (typeof args[args.length-1] === 'object') { if (typeof args[args.length-1] === 'object') {
isData = true; isData = true;
Expand All @@ -151,14 +60,16 @@ exports.identify = function(pathOrArgs, callback) {
if (isCustom) { if (isCustom) {
result = stdout; result = stdout;
} else { } else {
result = parseIdentify(stdout); var v = stdout.trim().split(' ');
geometry = result['geometry'].split(/x/); result = {

format: v[0],
result.format = result.format.match(/\S*/)[0] width: parseInt(v[1]),
result.width = parseInt(geometry[0]); height: parseInt(v[2]),
result.height = parseInt(geometry[1]); depth: parseInt(v[3])
result.depth = parseInt(result.depth); };
if (result.quality !== undefined) result.quality = parseInt(result.quality) / 100; if (v[4] !== "0") {
result.quality = parseInt(v[4]) / 100;
}
} }
} }
callback(err, result); callback(err, result);
Expand Down