1 #include <cstdio>
2 #include <cstring>
3 #include <stdint.h>
4 #include <windows.h>
5 int32_t width,height;
6 RGBQUAD *pixels;
7 bool OpenBitmap(char const *filename)
8 {
9 FILE *file = fopen(filename, "rb");
10 if (file)
11 {
12 width=0;
13 height=0;
14 BITMAPFILEHEADER bf;
15 BITMAPINFOHEADER bi;
16 fread(&bf, sizeof(bf), 1, file);
17 fread(&bi, sizeof(bi), 1, file);
18 if(bi.biBitCount!=24)
19 return false;
20 if(bi.biCompression!=BI_RGB)
21 return false;
22 width=bi.biWidth;
23 height=bi.biHeight;
24 pixels=new RGBQUAD[width*height];
25 uint32_t rowSize = (bi.biBitCount * width + 31) / 32 * 4;
26 uint8_t *line = new uint8_t[rowSize];
27 for (int y = 0; y < height; y++)
28 {
29 fread(line, rowSize, 1, file);
30 for (int x = 0; x < width; x++)
31 {
32 uint8_t *color = line + x * 3;
33 RGBQUAD *pixel = &pixels[(height-y-1) * width+x];
34 pixel->rgbBlue = color[0];
35 pixel->rgbGreen = color[1];
36 pixel->rgbRed = color[2];
37 }
38 }
39 delete[] line;
40 fclose(file);
41 return true;
42 }
43 return false;
44 }
45 RGBQUAD GetColor(int x, int y, int w, int h)
46 {
47 int r = 0, g = 0, b = 0;
48 for (int i = 0; i < w; i++)
49 {
50 if (i + x >= width) continue;
51 for (int j = 0; j < h; j++)
52 {
53 if (j + y >= height) continue;
54 RGBQUAD const& color = pixels[(y + j) * width + (x + i)];
55 r += color.rgbRed;
56 g += color.rgbGreen;
57 b += color.rgbBlue;
58 }
59 }
60 return RGBQUAD{r / (w * h), g / (w * h),b / (w * h)};
61 }
62 char ColorToCharacter(RGBQUAD const& color)
63 {
64 int brightness = (color.rgbRed + color.rgbGreen + color.rgbBlue) / 3;
65 static char const *characters = "Qo0V1;:*-. ";
66 int len = strlen(characters);
67 int span = 0xFF / len;
68 int cidx = brightness / span;
69 if (cidx == len)
70 cidx--;
71 return characters[cidx];
72 }
73 void OutputAscii(const char* filename, int w, int h)
74 {
75 FILE *file=fopen(filename,"a+");
76 int x = width / w;
77 int y = height / h;
78 for (int i = 0; i < height; i += y)
79 {
80 for (int j = 0; j < width; j += x)
81 {
82 RGBQUAD color = GetColor(j, i, x, y);
83 fprintf(file, "%c", ColorToCharacter(color));
84 //printf("%c", ColorToCharacter(color));
85 }
86 fprintf(file, "
");
87 //printf("
");
88 }
89 delete [] pixels;
90 fclose(file);
91 }
92 int main()
93 {
94 if(OpenBitmap("a.bmp"))
95 OutputAscii("a.txt",width/6,height/12);
96 return 0;
97 }