-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (75 loc) · 2.22 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
const Canvas = require('canvas');
const fs = require('fs');
const unique = require('lodash.uniqby');
const Color = require('color');
const idGenerator = require('incremental-id-generator');
const nextID = idGenerator('abcdefghijklmnopqrstuvwxyz');
let colors = [];
const files = {
};
let colorMap = new Map();
function readData(path) {
const filename = path.split(/[\\/]/).pop().split('.').shift();
const Image = Canvas.Image;
const pic = fs.readFileSync(path);
const img = new Image();
img.src = pic;
files[filename] = img;
const width = img.width;
const height = img.height;
const canvas = new Canvas(width, height);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const data = ctx.getImageData(x, y, 1, 1).data;
const color = Color(`rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3]})`);
colors.push(color)
}
}
colors = unique(colors, (color) => color.string());
}
module.exports = (arr) => {
arr.forEach(readData);
colorMap = colors.reduce((map, color) => {
map.set(color.rgb().string(), nextID());
return map;
}, colorMap);
printColorMap(colorMap);
printFilesScss(files);
};
function printColorMap(map) {
console.log(`$colors: (`);
for (let [color, code] of map) {
console.log(` '${code}': '${color}',`);
}
console.log(`);`)
}
function printImage(img) {
const Image = Canvas.Image;
const width = img.width;
const height = img.height;
const canvas = new Canvas(width, height);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
for (let y = 0; y < width; y++) {
let row = ` (`;
for (let x = 0; x < height; x++) {
const data = ctx.getImageData(x, y, 1, 1).data;
const color = Color(`rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3]})`);
const char = colorMap.get(color.rgb().string());
row = `${row} ${char}`;
}
row = `${row})`;
console.log(row);
}
}
function printFilesScss(data) {
console.log(`$pixel-art: (`);
Object.keys(data).forEach(file => {
console.log(` ${file}: (`)
printImage(data[file]);
console.log(` ),`)
});
console.log(`);`);
}