-
Notifications
You must be signed in to change notification settings - Fork 0
/
square-image-loader.js
82 lines (65 loc) · 1.72 KB
/
square-image-loader.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
'use strict';
import colors from 'colors';
import PNGImage from 'pngjs-image';
import fs from 'fs-extra';
import path from 'path';
import * as color_convert from './color-convert.js';
async function load(color_map, folder) {
console.log(`reading images from ${folder}`);
const images = await loadImages(folder);
const width = images[0].getWidth();
const height = images[0].getHeight()
let pixels = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let pixel_colors = [];
for (let image of images) {
// this returns ABGR color
let abgr = image.getAt(x, y) >>> 0;
let argb = color_convert.ABGRtoARGB(abgr);
let char = color_map[argb];
if (char !== undefined) {
pixel_colors.push(char);
} else {
throw new Error(`ARGB: ${color_convert.toHexString(argb)} ABGR: ${color_convert.toHexString(abgr)} is not in color map ${Object.keys(color_map).map(color_convert.toHexString).join(', ')}`);
}
}
const obj = {
x: x / width,
y: y / height,
pixel_colors,
}
pixels.push(obj);
}
}
const subsequence_length = images.length;
return {
subsequence_length,
pixels,
image_size: {
width, height
}
};
}
async function loadImages(dir) {
const files = await fs.readdir(dir);
const loads = files
.sort()
.map( file => path.join(dir, file))
.filter(file => path.extname(file) === '.png')
.map( file => readImage(file));
const images = await Promise.all(loads)
return images;
}
async function readImage(path) {
return new Promise((resolve, reject) => {
PNGImage.readImage(path, function (err, image) {
if (err) return reject(err);
if (!image) return reject(new Error('No image'));
resolve(image);
});
});
}
export {
load,
}