如何使用bmp位图制作字符画

来源:互联网 发布:世界进出口数据 编辑:程序博客网 时间:2024/04/29 17:32

前言

最近有个大胆的想法,就是用C语言将bmp图转变为字符画,大概的原理就是将每个像素点转变为灰度不同的字符,然后我便开始了研究


原理

BMP图又称为Bitmap位图,是Windows系统的一种图像文件格式,其中的数据根据官方文档可以分为四部分:

名称 大小(Byte) bmp file header 14 bitmap information 40 color palette 根据实际决定 bitmap data 根据实际决定

结构

从网上搜寻到的图片可知
bmp file header的详细内容为

名称 大小(Byte) 作用 bfType 2 BM代表Windows bfSize 4 该位图的大小 bfReserved1 2 保留 bfReserved2 2 保留 bfOffBits 4 从头到图像的偏移量

而bmp information的部分有用内容为

名称 大小(Byte) 作用 biSize 4 BM代表Windows biWidth 4 该位图的宽度(像素) biHeight 4 该位图的高度(像素)

接着调速板就是一张映射表,我们根据位图数据来确定每一个像素点的颜色


注意点

除此以外,还要注意的东西有对齐规则和bmp的类型


代码

#include <stdio.h>#include <stdbool.h>#include <stdlib.h>#pragma pack(2)typedef unsigned short WORD;typedef unsigned int DWORD;typedef unsigned char BYTE;typedef struct BMP_FILE_HEADER{    WORD bType;     DWORD bSize;     WORD bReserved1;     WORD bReserved2;     DWORD bOffset; } BMPFILEHEADER;typedef struct BMP_INFO{    DWORD bInfoSize;     DWORD bWidth;     DWORD bHeight;     WORD bPlanes;     WORD bBitCount;     DWORD bCompression;     DWORD bmpImageSize;     DWORD bXPelsPerMeter;     DWORD bYPelsPerMeter;     DWORD bClrUsed;    DWORD bClrImportant; } BMPINFO;typedef struct BGR_INFO{    BYTE blue;    BYTE green;    BYTE red;}BGRINFO;#define NUM_CHAR 20BMPFILEHEADER bmpFileHeader;BMPINFO bmpInfo;BGRINFO bgrinfoTest;//char ch[71]="$@B%8&WM#*ZO0QLCJUYXoahkbdpqwmzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";char ch[NUM_CHAR+1]="@&#80o;:+=~-*^\"`',. ";int main(int argc,char *argv[]){    FILE *fp,*fp1;    if((fp=fopen("4.bmp","rb"))==NULL){        printf("要转换的图片不存在");        exit(EXIT_FAILURE);    }    if((fp1=fopen("4.txt","w"))==NULL){        printf("存照片文档不存在");        exit(EXIT_FAILURE);    }    fseek(fp,0,0);    fread(&bmpFileHeader,sizeof(BMPFILEHEADER),1,fp);    fread(&bmpInfo,sizeof(BMPINFO),1,fp);    BGRINFO bgrinfo[bmpInfo.bWidth][bmpInfo.bHeight];    int color[bmpInfo.bWidth][bmpInfo.bHeight];    int grey;    int useless=(bmpInfo.bWidth*3%4==0)?0:(4-bmpInfo.bWidth*3%4);    printf("%d %d",bmpInfo.bWidth,bmpInfo.bHeight);    for(int j=0;j<bmpInfo.bHeight;j++){        for(int i=0;i<bmpInfo.bWidth;i++){            fread(&bgrinfo[i][j],sizeof(BGRINFO),1,fp);            grey=(bgrinfo[i][j].blue*11+bgrinfo[i][j].green*59+bgrinfo[i][j].red*30+50)/100;            color[i][bmpInfo.bHeight-j-1]=grey;        }        fseek(fp,useless,SEEK_CUR);    }    for(int j=0;j<bmpInfo.bHeight;j++){        for(int i=0;i<bmpInfo.bWidth;i++){            fprintf(fp1,"%c%c",ch[(NUM_CHAR-1)*color[i][j]/255],ch[8*color[i][j]/255]);        }        fprintf(fp1,"\n");    }    fclose(fp);    fclose(fp1);    return 0;}

效果图

这里写图片描述