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
|
var MircColor = (function(){
var COLORS = [
[255,255,255],
[0,0,0],
[0,0,127],
[0,147,0],
[255,0,0],
[127,0,0],
[156,0,156],
[252,127,0],
[255,255,0],
[0,252,0],
[0,147,147],
[0,255,255],
[0,0,252],
[255,0,255],
[127,127,127],
[210,210,210]
]
function closest_to(pixel){
return COLORS.reduce(function(prev, curr, index) {
var d = distance(pixel, curr)
if (prev[0] > d) {
prev[0] = d
prev[1] = index
}
return prev
}, [Infinity, -1])[1]
}
function distance(u, v){
var r = u[0] - v[0]
var g = u[1] - v[1]
var b = u[2] - v[2]
return Math.sqrt(r*r+g*g+b*b)
}
function fromImageData (pixels, cb){
var rows = [],
pixel = new Array (4),
data = pixels.data,
t
console.log(pixels)
for (var i = 0, h = pixels.height; i < h; i++) {
var row = []
rows.push(row)
for (var j = 0, w = pixels.width; j < w; j++) {
t = (i*w+j)*4
pixel[0] = data[t]
pixel[1] = data[t+1]
pixel[2] = data[t+2]
pixel[3] = data[t+3]
row[j] = closest_to(pixel)
}
}
console.log(rows)
if (! cb) return rows
else cb (rows)
}
function fromUrl (url, cb, width) {
var img = new Image ()
img.onload = function(){
var canvas = document.createElement("canvas"), ctx = canvas.getContext('2d')
if (width) {
canvas.width = width
canvas.height = img.naturalHeight * width / img.naturalWidth / 2
}
else {
canvas.width = img.naturalWidth * 2
canvas.height = img.naturalHeight
}
ctx.drawImage(img,0,0,img.naturalWidth,img.naturalHeight,0,0,canvas.width,canvas.height)
var pixels = ctx.getImageData(0,0,canvas.width,canvas.height)
fromImageData(pixels, cb)
}
img.src = url
}
function ascii (rows) {
var lines = rows.map(function(str){
return str.map(function(index){ return "\\x03" + index + "," + index + "x\\x03" }).join("")
}).join("\\n")
var txt = '/exec -out printf "' + lines + '"\n'
return txt
}
function asciiFromUrl (url, cb, width) {
fromUrl(url, function(rows){
cb(ascii(rows), rows)
}, width)
}
function stringFromUrl (url, cb, width) {
fromUrl(url, function(rows){
cb(rows.map(function(str){
return str.map(function(index){ return "\C-c" + index + "," + index + "x\C-c" }).join("")
}).join("\n"))
}, width)
}
return {
colors: COLORS,
closest_to: closest_to,
distance: distance,
fromUrl: fromUrl,
fromImageData: fromImageData,
stringFromUrl: stringFromUrl,
asciiFromUrl: asciiFromUrl,
ascii: ascii,
}
})()
|