-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (86 loc) · 2.73 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
'use strict';
var os = require('os');
var path = require('path');
var _ = require('lodash');
var detectFace = require('./lib/face.js');
var detectPhash = require('./lib/phash.js');
var pkg = require('./package.json');
var async = require('neo-async');
var mkdirp = require('mkdirp');
/**
* Creates ImageTag instance,
*
* @param {Object} options:
* @param {String} tmpDir - directory to save files for phash processing
* @param {Boolean} phash - should we calculated phash? Default: true
* @param {Boolean} face - should we find face positions? Default: true
*/
function ImageTag(options, done) {
if (!this instanceof ImageTag) {
return new ImageTag(options, done);
}
done = done || function imageTagInstanceCreated(err) {
if (err) {
throw err;
}
};
var opts = this.options = _.defaults(options || {}, {
face: true,
size: true,
faceProfiles: false,
phash: true,
phashBinary: true,
tmpDir: path.resolve(os.tmpdir(), pkg.name, pkg.version)
});
if (!opts.face && !opts.phash) {
return setImmediate(done, new Error('at `face` or `phash` must be set to true'));
}
if (!opts.phash) {
return setImmediate(done);
}
mkdirp(opts.tmpDir, done);
}
/**
* Detects face and phash of imageBuffer
* @param {Buffer} imageBuffer - binary data of image in jp(e)g / png format
* @param {Function} next - <err, imageData>
*/
ImageTag.prototype.detect = function (imageBuffer, next) {
if (!Buffer.isBuffer(imageBuffer) || imageBuffer.length < 1) {
return setImmediate(next, new Error('first argument must be a non-empty buffer'));
}
var output = {};
var options = this.options;
async.parallel({
face: function (callback) {
if (!options.face) {
return callback();
}
detectFace(imageBuffer, options, function detectFaceCallback(err, faceData) {
if (err) {
return callback(err);
}
_.extend(output, faceData);
callback();
});
},
phash: function (callback) {
if (!options.phash) {
return callback();
}
detectPhash(imageBuffer, options, function detectPhashCallback(err, phashData) {
if (err) {
return callback(err);
}
_.extend(output, phashData);
callback();
});
}
}, function detectionCallback(err) {
if (err) {
return setImmediate(next, err);
}
setImmediate(next, null, output);
});
};
module.exports = ImageTag;