#include #include #include #include #include #include #include "bmp2txt.h" static font_t* load_font(char* filename); /* Initializes bmp2txt */ font_t* init_bmp2txt(void) { return load_font("font"); } /* Shuts down bmp2txt */ void cleanup_bmp2txt(font_t* font) { free(font); } /* Plots an 8bpp grayscale BITMAP to screen using the given font */ void asciify_bmp(font_t* font, BITMAP* img) { int y, x, v; int i = -1; printf("\033[H"); for (y = 0; y < img->h; y++) { for (x = 0; x < img->w; x++) { v = getpixel(img, x, y); if (v < 36) { putchar(' '); continue; } else if (v < 36 * 2) { if (i != 0) {printf("\033[1;30m"); i = 0;} } else if (v < 36 * 3) { if (i != 1) {printf("\033[0;34m"); i = 1;} } else if (v < 36 * 4) { if (i != 2) {printf("\033[1;34m"); i = 2;} } else if (v < 36 * 5) { if (i != 3) {printf("\033[0;36m"); i = 3;} } else if (v < 36 * 6) { if (i != 4) {printf("\033[1;36m"); i = 4;} } else if (v < 36 * 7) { if (i != 5) {printf("\033[1;37m"); i = 5;} } putchar(font[v]); } putchar('\n'); } fflush(stdout); } /* Load a font and return a map */ static font_t* load_font(char* filename) { FILE* ffile = fopen(filename, "rb"); int i, j, y, x, c, v, e; int min = -1, max = -1; int* font_count = malloc(sizeof(int) * 256); int* font_map = malloc(sizeof(int) * 256); /* Count number of set pixels in each glyph */ for (i = 0; i < 256; i++) { font_count[i] = 0; for (y = 0; y < 16; y++) { c = fgetc(ffile); for (x = 0; x < 8; x++) if (c & (1 << x)) font_count[i]++; } if (!isprint(i)) {font_count[i] = -1; continue;} if (min == -1 || min > font_count[i]) min = font_count[i]; if (max == -1 || max < font_count[i]) max = font_count[i]; } /* Map values 0 - 255 to glyphs */ for (i = 0; i < 256; i++) { /* Detarmine target value */ v = (max - min) * i / 255 + min; /* Find nearest match to target value */ e = -1; for (j = 0; j < 256; j++) { if (font_count[j] < 0) continue; if (e == -1 || abs(font_count[j] - v) < e) { e = abs(font_count[j] - v); font_map[i] = j; } } } free(font_count); fclose(ffile); return font_map; }