將愛心圖片(位圖)讀入內存,按亮度映射為字符集 " .:-=+*#%@"(由淺到深),逐行輸出到控制台。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WIDTH 80
#define HEIGHT 40
const char *RAMP = " .:-=+*#%@";
unsigned char *load_bmp(const char *path, int *w, int *h) {
FILE *fp = fopen(path, "rb");
if (!fp) return NULL;
fseek(fp, 18, SEEK_SET);
fread(w, 4, 1, fp);
fread(h, 4, 1, fp);
fseek(fp, 54, SEEK_SET);
int row = ((*w * 3 + 3) / 4) * 4;
unsigned char *data = malloc(row * *h);
fread(data, row, *h, fp);
fclose(fp);
return data; // BGR 格式,底部在前
}
int main() {
int w, h;
unsigned char *img = load_bmp("heart.bmp", &w, &h);
if (!img) { puts("圖片讀取失敗"); return 1; }
int row = ((w * 3 + 3) / 4) * 4;
for (int y = h - 1; y >= 0; y--) { // BMP 底部在前,需倒序
for (int x = 0; x < w; x++) {
unsigned char *p = img + y * row + x * 3;
int gray = (p[0] + p[1] + p[2]) / 3; // 簡單灰度
int idx = gray * (strlen(RAMP) - 1) / 255;
putchar(RAMP[idx]);
}
putchar('\n');
}
free(img);
return 0;
}
row_stridegcc heart.c -o heart && ./heartheart.bmp 放在可執行文件同級目錄heart.exe字符畫本質是「圖片灰度映射」。掌握 BMP 讀取、行填充、灰度映射三步,即可將任意圖片轉為控制台藝術。愛心圖片可用畫圖工具繪製或網上下載,命名為 heart.bmp 放在項目根目錄即可。