在没有其他库的情况下以纯c / c ++编写BMP图像

在我的算法中,我需要创建信息输出。我必须在bmp文件中写入布尔矩阵。它必须是单色图像,如果该元素上的矩阵为真,则像素为白色。主要问题是bmp标头以及如何编写此标头。


德玛西亚99
浏览 573回答 3
3回答

一只斗牛犬

看看这是否对您有用...在这段代码中,我有3个二维数组,分别称为red,green和blue。每个元素的大小为[width] [height],每个元素对应一个像素-我希望这是有道理的!FILE *f;unsigned char *img = NULL;int filesize = 54 + 3*w*h;&nbsp; //w is your image width, h is image height, both intimg = (unsigned char *)malloc(3*w*h);memset(img,0,3*w*h);for(int i=0; i<w; i++){&nbsp; &nbsp; for(int j=0; j<h; j++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; x=i; y=(h-1)-j;&nbsp; &nbsp; &nbsp; &nbsp; r = red[i][j]*255;&nbsp; &nbsp; &nbsp; &nbsp; g = green[i][j]*255;&nbsp; &nbsp; &nbsp; &nbsp; b = blue[i][j]*255;&nbsp; &nbsp; &nbsp; &nbsp; if (r > 255) r=255;&nbsp; &nbsp; &nbsp; &nbsp; if (g > 255) g=255;&nbsp; &nbsp; &nbsp; &nbsp; if (b > 255) b=255;&nbsp; &nbsp; &nbsp; &nbsp; img[(x+y*w)*3+2] = (unsigned char)(r);&nbsp; &nbsp; &nbsp; &nbsp; img[(x+y*w)*3+1] = (unsigned char)(g);&nbsp; &nbsp; &nbsp; &nbsp; img[(x+y*w)*3+0] = (unsigned char)(b);&nbsp; &nbsp; }}unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0};unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0};unsigned char bmppad[3] = {0,0,0};bmpfileheader[ 2] = (unsigned char)(filesize&nbsp; &nbsp; );bmpfileheader[ 3] = (unsigned char)(filesize>> 8);bmpfileheader[ 4] = (unsigned char)(filesize>>16);bmpfileheader[ 5] = (unsigned char)(filesize>>24);bmpinfoheader[ 4] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;w&nbsp; &nbsp; );bmpinfoheader[ 5] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;w>> 8);bmpinfoheader[ 6] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;w>>16);bmpinfoheader[ 7] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;w>>24);bmpinfoheader[ 8] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;h&nbsp; &nbsp; );bmpinfoheader[ 9] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;h>> 8);bmpinfoheader[10] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;h>>16);bmpinfoheader[11] = (unsigned char)(&nbsp; &nbsp; &nbsp; &nbsp;h>>24);f = fopen("img.bmp","wb");fwrite(bmpfileheader,1,14,f);fwrite(bmpinfoheader,1,40,f);for(int i=0; i<h; i++){&nbsp; &nbsp; fwrite(img+(w*(h-i-1)*3),3,w,f);&nbsp; &nbsp; fwrite(bmppad,1,(4-(w*3)%4)%4,f);}free(img);fclose(f);
打开App,查看更多内容
随时随地看视频慕课网APP