-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.ts
389 lines (353 loc) Β· 12.2 KB
/
mod.ts
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import { colors, stringWidth, tty } from "./deps.ts";
import {
decodeImageFromPath,
decodeImageFromRawFile,
decodeImageFromRawPixels,
} from "./decode.ts";
interface imageSettings {
/** The local file path or URL of the image */
path?: string;
/** The raw data of a PNG or JPG image */
rawFile?: Uint8Array;
/** The raw data for the image: the rgb(a) array as well as the height and width */
rawPixels?: rawPixelData;
/** The character map to use when outputting the image */
characterMap?: string | string[];
/** The number of characters wide the output image is */
width?: number;
/** whether the character map should be inverted */
inverted?: boolean;
/** Whether the output image should be in color */
color?: boolean;
/** The alpha threshold for considering a pixel transparent or opaque */
transparencyThreshold?: number;
/** The number of times the image should loop if it is an animation */
animationLoops?: number;
}
interface rawPixelData {
width: number;
height: number;
data: Uint8Array;
}
interface rgba {
r: number;
g: number;
b: number;
a: number;
}
interface groupColor {
id: number;
neighbors: {
color: rgba;
id: number;
}[];
added: boolean;
color: rgba;
}
const MIN_AUTO_WIDTH = 12;
/** Returns a promise which resolves to a string version of the image that can outputted to the console. */
async function getImageStrings(settings: imageSettings): Promise<string[]> {
const characterMap = settings.characterMap
? [...settings.characterMap]
: undefined;
const inverted = settings.inverted ?? false;
const color = settings.color ?? true;
const transparencyThreshold = settings.transparencyThreshold ?? 1;
let decodedImage;
if (typeof settings.path !== "undefined") {
decodedImage = await decodeImageFromPath(settings.path);
} else if (typeof settings.rawFile !== "undefined") {
decodedImage = await decodeImageFromRawFile(settings.rawFile);
} else if (typeof settings.rawPixels !== "undefined") {
decodedImage = await decodeImageFromRawPixels(settings.rawPixels);
} else {
throw new Error("No file path or raw data specified.");
}
const imagePixelWidth = decodedImage.width;
const imagePixelHeight = decodedImage.height;
let characterWidth;
if (settings.width) {
characterWidth = imagePixelWidth / settings.width;
} else {
//currently requires --unstable
const terminalWidth = Deno.consoleSize(Deno.stdout.rid).columns;
const terminalHeight = Deno.consoleSize(Deno.stdout.rid).rows;
characterWidth =
(terminalWidth < Math.max(terminalHeight, MIN_AUTO_WIDTH) * 2)
? imagePixelWidth / terminalWidth
: imagePixelHeight / (Math.max(terminalHeight, MIN_AUTO_WIDTH) - 2) / 2;
}
const outputStrings: string[] = [];
for (let frameIndex = 0; frameIndex < decodedImage.numFrames; frameIndex++) {
let outputString = "";
for (
let y = characterWidth;
y <= imagePixelHeight - characterWidth;
y += characterWidth * 2
) {
for (
let x: number = characterWidth / 2;
x <= imagePixelWidth - characterWidth / 2;
x += 0
) {
let char: string;
if (characterMap === undefined) {
const values = [
decodedImage.getPixel(
Math.floor(x - characterWidth / 4),
Math.floor(y - characterWidth / 2),
frameIndex,
),
decodedImage.getPixel(
Math.floor(x + characterWidth / 4),
Math.floor(y - characterWidth / 2),
frameIndex,
),
decodedImage.getPixel(
Math.floor(x - characterWidth / 4),
Math.floor(y + characterWidth / 2),
frameIndex,
),
decodedImage.getPixel(
Math.floor(x + characterWidth / 4),
Math.floor(y + characterWidth / 2),
frameIndex,
),
];
const organisedValues = calculateGroups(values);
let characterIndex = 0;
const group0TotalColor = {
r: 0,
g: 0,
b: 0,
a: 0,
};
const group1TotalColor = {
r: 0,
g: 0,
b: 0,
a: 0,
};
let group0Count = 0;
let group1Count = 0;
for (const value of organisedValues) {
if (value.group === 0) {
group0TotalColor.r += value.color.r;
group0TotalColor.g += value.color.g;
group0TotalColor.b += value.color.b;
group0TotalColor.a += value.color.a;
group0Count++;
} else {
group1TotalColor.r += value.color.r;
group1TotalColor.g += value.color.g;
group1TotalColor.b += value.color.b;
group1TotalColor.a += value.color.a;
group1Count++;
}
}
const backgroundColor = {
r: group0TotalColor.r / group0Count,
g: group0TotalColor.g / group0Count,
b: group0TotalColor.b / group0Count,
a: group0TotalColor.a / group0Count,
};
const foregroundColor = {
r: group1TotalColor.r / group1Count,
g: group1TotalColor.g / group1Count,
b: group1TotalColor.b / group1Count,
a: group1TotalColor.a / group1Count,
};
/*
Some terminals (e.g. the one in VSCode) leave a gap beneath the characters.
(Although most don't.) As a result, the background should be the same as
color at the bottom of the cell, so there isn't a sudden change in color
at the bottom of each character.
By default, group 1 is the foreground and group 0 is the background,
but if the bottom of the cell is all group 1, this should be switched.
If the foreground color is transparent, we need to switch colors as well,
since only the background can be displayed transparently.
*/
const switchColors = (organisedValues[2].group === 1 &&
organisedValues[3].group === 1 &&
backgroundColor.a > transparencyThreshold) ||
foregroundColor.a < transparencyThreshold;
for (const value of organisedValues) {
characterIndex += 2 ** value.id *
(switchColors ? 1 - value.group : value.group);
}
if (!color) {
const backgroundLightness = colorLightness(backgroundColor);
const foregroundLightness = colorLightness(foregroundColor);
backgroundColor.r = backgroundLightness;
backgroundColor.g = backgroundLightness;
backgroundColor.b = backgroundLightness;
foregroundColor.r = foregroundLightness;
foregroundColor.g = foregroundLightness;
foregroundColor.b = foregroundLightness;
}
char = " βββββββββββββββ"[characterIndex];
if (
backgroundColor.a < transparencyThreshold &&
foregroundColor.a < transparencyThreshold
) {
char = " ";
} else if (backgroundColor.a < transparencyThreshold) {
char = colors.rgb24(char, foregroundColor);
} else if (foregroundColor.a < transparencyThreshold) {
char = colors.rgb24(char, backgroundColor);
} else {
char = colors.bgRgb24(
colors.rgb24(char, foregroundColor),
backgroundColor,
);
if (switchColors) char = colors.inverse(char);
}
} else {
const pixelColor = decodedImage.getPixel(
Math.floor(x),
Math.floor(y),
frameIndex,
);
const grayscaleValue = colorLightness(pixelColor);
if (grayscaleValue === undefined) {
throw `Error parsing pixel (${x}, ${y})`;
}
let characterIndex = Math.floor(
grayscaleValue / 255 * (characterMap.length - 0.5),
);
characterIndex = inverted
? characterMap.length - 1 - characterIndex
: characterIndex;
char = color
? colors.rgb24(characterMap[characterIndex], pixelColor)
: characterMap[characterIndex];
}
outputString += char;
x += characterWidth * stringWidth(char);
}
if (y < imagePixelHeight - characterWidth) outputString += "\n";
}
outputStrings.push(outputString);
}
return outputStrings;
}
/*
This function splits the four colors of a cell into two groups,
which are used to decide a background and foreground color,
and choose which character to use to display the cell.
The algorithm used below tries to make the two groups
have similar colors within the group.
*/
function calculateGroups(values: rgba[]) {
const groups: groupColor[][] = [
[],
[],
];
const allSortedNeighbors = values.map((color, idA) => {
const neighbors = values.map((color, id) => {
return {
color,
id,
};
}).filter((_, idB) => idA !== idB).sort(
(v1, v2) =>
colorDistance(color, v1.color) - colorDistance(color, v2.color),
);
return {
id: idA,
neighbors,
added: false,
color,
};
});
for (const c1 of allSortedNeighbors) {
if (!c1.added) {
for (const c2 of allSortedNeighbors) {
if (c1.id !== c2.id && !c2.added) {
//both each others' closest neighbor
if (c1.neighbors[0].id === c2.id && c2.neighbors[0].id === c1.id) {
if (groups[0].length === 0) {
groups[0].push(c1);
groups[0].push(c2);
} else {
groups[1].push(c1);
groups[1].push(c2);
}
c1.added = true;
c2.added = true;
}
}
}
}
}
const remainingColors = allSortedNeighbors.filter((v) => !v.added);
if (remainingColors.length > 0) {
const group0Average = {
r: (groups[0][0].color.r + groups[0][1].color.r) / 2,
g: (groups[0][0].color.g + groups[0][1].color.g) / 2,
b: (groups[0][0].color.b + groups[0][1].color.b) / 2,
a: (groups[0][0].color.a + groups[0][1].color.a) / 2,
};
if (
colorDistance(remainingColors[0].color, group0Average) <
colorDistance(remainingColors[1].color, group0Average)
) {
groups[0].push(remainingColors[0]);
groups[1].push(remainingColors[1]);
} else {
groups[0].push(remainingColors[1]);
groups[1].push(remainingColors[0]);
}
}
return [
...groups[0].map((v: groupColor) => {
return {
...v,
group: 0,
};
}),
...groups[1].map((v: groupColor) => {
return {
...v,
group: 1,
};
}),
].sort((v1, v2) => v1.id - v2.id);
}
/** Outputs the image to the console. */
async function printImage(settings: imageSettings): Promise<void> {
const outputStrings = await getImageStrings(settings);
return new Promise((resolve) => {
//const width = stringWidth(outputStrings[0].split("\n")[0]);
const height = (outputStrings[0]?.match(/\n/g)?.length ?? 0) + 1;
tty.hideCursorSync();
//If it is an animation, add an extra frame so we end where we started.
const numFrames = outputStrings.length === 1
? 1
: outputStrings.length * (settings.animationLoops ?? 1) + 1;
for (let frameIndex = 0; frameIndex < numFrames; frameIndex++) {
setTimeout(async () => {
console.log(outputStrings[frameIndex % outputStrings.length]);
if (frameIndex === numFrames - 1) {
// tty.goDownSync(height + 2);
await tty.showCursor();
resolve();
} else {
tty.goUpSync(height);
}
}, frameIndex * 200);
}
});
}
function colorDistance(color1: rgba, color2: rgba) {
//calculate the visual distance between colors using pythagoras's theorem in rgba space
//not totally accurate but it's fast and simple
return ((color1.r - color2.r) ** 2 + (color1.g - color2.g) ** 2 +
(color1.b - color2.b) ** 2 +
(color1.a - color2.a) ** 2) ** 0.5;
}
function colorLightness(color: rgba) {
return (color.r + color.g + color.b) / 3;
}
export { getImageStrings, printImage };
export type { imageSettings };