-
Notifications
You must be signed in to change notification settings - Fork 2
/
image.js
55 lines (51 loc) · 1.61 KB
/
image.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
const Jimp = require('jimp');
function rgbToAnsi256(r, g, b) {
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round(((r - 8) / 247) * 24) + 232;
}
var ansi = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
return ansi;
}
/**
*
* @param {String|Buffer|Jimp} image
* @param {Number} [width]
* @param {*} [height]
* @returns {String} The image as a string of ANSI escape codes
*/
async function Image(image, width, height) {
width = width || process.stdout.columns;
height = height || process.stdout.rows;
var resize = width !== process.stdout.columns;
return new Promise((resolve, reject) => {
var pixels = [];
var result = "";
Jimp.read(image, (err, image) => {
if (err) throw err;
image = image.resize(width, height)
image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
var red = this.bitmap.data[idx + 0];
var green = this.bitmap.data[idx + 1];
var blue = this.bitmap.data[idx + 2];
pixels.push(rgbToAnsi256(red, green, blue))
});
pixels.forEach((item, i) => {
result = result + "\033[48;5;" + item + "m \033[0;00m"
if (resize && i % width === width - 1) {
result = result + '\n'
}
});
return resolve(result)
})
})
}
module.exports = Image;