forked from Munter/node-histogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
124 lines (107 loc) · 4 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*global Canvas, define*/
(function () {
var Canvas,
getCanvasImageData = function (imageBuffer, callback) {
var canvasImage = new Canvas.Image();
canvasImage.onerror = callback;
canvasImage.onload = function () {
var context = new Canvas(canvasImage.width, canvasImage.height).getContext('2d');
context.drawImage(canvasImage, 0, 0);
callback(null, context.getImageData(0, 0, canvasImage.width, canvasImage.height).data);
};
canvasImage.src = imageBuffer;
},
histogram = function (imageBuffer, callback) {
getCanvasImageData(imageBuffer, function (err, data) {
if (err) {
return callback(err);
}
var hist = {
red: new Array(256),
green: new Array(256),
blue: new Array(256),
alpha: new Array(256),
colors: {
rgb: 0,
rgba: 0
},
palettes: {
rgb: [],
rgba: []
},
greyscale: true,
alphachannel: false
},
red,
green,
blue,
alpha,
hexmap = {},
hexamap = {},
i;
for (i = 0; i < 256; i += 1) {
hist.red[i] =
hist.green[i] =
hist.blue[i] =
hist.alpha[i] = 0;
}
for (i = 0; i < data.length; i += 4) {
red = data[i];
green = data[i + 1];
blue = data[i + 2];
alpha = data[i + 3];
if (alpha < 255) {
hist.alphachannel = true;
}
if (hist.greyscale && red !== green || red !== blue) {
hist.greyscale = false;
}
hist.red[red] += 1;
hist.green[green] += 1;
hist.blue[blue] += 1;
hist.alpha[alpha] += 1;
var hexaString = (red * 0x1000000 + green * 0x10000 + blue * 0x100 + alpha).toString(16),
hexa = '#' + ('0000000'.substr(0, 8 - hexaString.length)) + hexaString,
hex = hexa.substr(0, 7);
if (!(hex in hexmap)) {
hexmap[hex] = 1;
hist.palettes.rgb.push(hex);
hist.colors.rgb += 1;
} else {
hexmap[hex] += 1;
}
if (!(hexa in hexamap)) {
hexamap[hexa] = 1;
hist.palettes.rgba.push(hexa);
hist.colors.rgba += 1;
} else {
hexamap[hexa] += 1;
}
}
callback(null, hist);
});
};
if (typeof window === 'undefined') {
Canvas = require('canvas');
} else {
// Polyfill canvas constructor
Canvas = function (width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
};
Canvas.Image = Image;
}
if (typeof module !== 'undefined') {
module.exports = histogram;
} else if (typeof define === 'function') {
// AMD module
define([], function () {
return histogram;
});
} else if (window) {
// Fall back to installing histogram in window scope
window.histogram = histogram;
}
}());