-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathasciize.js
71 lines (61 loc) · 1.82 KB
/
asciize.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
var colors = require('./node_modules/blessed/lib/colors');
function asciize(image, width, height) {
var countedColors = countColors(image, width, height)
, ascii = ''
, ansiColorCode
, previousColor = -2;
for (var i = 0; i < countedColors.length; i++) {
ansiColorCode = sortColors(countedColors[i])[0].color;
if (ansiColorCode !== previousColor) {
ascii += '\033[38;5;' + ansiColorCode + 'm';
previousColor = ansiColorCode;
}
ascii += '#';
}
return ascii + '\033[0m';
}
function sortColors(countedColors) {
var sortedColors = []
, color;
for (color in countedColors) {
sortedColors.push({'color': color, 'count': countedColors[color]});
}
return sortedColors.sort(s);
function s(a, b) {
if (a.count < b.count) {
return 1;
} else if (a.count > b.count) {
return -1;
}
return 0;
}
}
function countColors(image, width, height) {
var colorCount = []
, blockWidth = image.width / width
, blockHeight = image.height / height
, index = 0
, pixelIndex
, pixelColor;
for (var i = 0; i < image.pixels.length; i += 3) {
pixelIndex = i / 3;
index = Math.floor(pixelIndex / blockWidth) % width +
Math.floor(pixelIndex / image.width / blockHeight) * width;
if (!colorCount[index]) {
colorCount[index] = {};
}
pixelColor = colors.match(image.pixels[i], image.pixels[i + 1], image.pixels[i + 2]);
if (!(pixelColor in colorCount[index])) {
colorCount[index][pixelColor] = 0;
}
// Assign less weight to grayscale values for a more interesting picture
if (pixelColor >= 232 || pixelColor === 59) {
colorCount[index][pixelColor] += .5;
} else {
colorCount[index][pixelColor]++;
}
}
return colorCount;
}
exports.asciize = asciize;
exports.sortColors = sortColors;