-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
54 lines (46 loc) · 1.6 KB
/
script.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
var input = document.getElementById('file-input');
var result = document.getElementById('result');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
input.addEventListener('change', function() {
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener('load', function () {
var img = new Image();
img.src = reader.result;
img.addEventListener('load', function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
console.time('processImage');
processImage(img);
console.timeEnd('processImage');
}, false);
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
function processImage(img) {
var chars = [' ', '\'', '.', ':', '|', 'T', 'X', '0', '#'];
var width = img.width;
var height = img.height;
var markup = '';
// in here our scale is 3 - it means we count only 1 of 3 pixels
for(var y = 0; y < height; y += 3) {
for(var x = 0; x < width; x += 3) {
// get rgb
var pixel = ctx.getImageData(x, y, 1, 1);
var data = pixel.data;
var r = data[0];
var g = data[1];
var b = data[2];
// get the relevant character
var index = Math.floor((r + g + b) * (chars.length - 1) /(255 * 3));
var ch = chars[index];
markup += `<span style="color:rgb(${r}, ${g}, ${b})">${ch}</span>`;
}
markup += '<br>';
}
result.innerHTML = markup;
}