Creating a Monochromatic BMP Image in Pure C/C
Bitmap image files are widely used for storing digital images. This article addresses the need to write a boolean matrix into a monochrome BMP file, where pixels are set to white if the corresponding matrix element is true.
Understanding the BMP Header
The BMP file format has a specific header structure that contains essential information about the image. The header consists of two parts: the file header and the information header.
The File Header
The Information Header
Creating the Monochrome BMP
To create the monochrome BMP:
Example Code
The following C/C code demonstrates the creation of a monochrome BMP from a boolean matrix:
#include <stdio.h> #include <stdlib.h> int main() { FILE *f; unsigned char *img = NULL; int filesize = 54 + 3*w*h; //w is your image width, h is image height, both int img = (unsigned char *)malloc(3*w*h); memset(img,0,3*w*h); for(int i=0; i<w; i++) { for(int j=0; j<h; j++) { bool = matrix[i][j] x=i; y=(h-1)-j; r = bool? 255 : 0; g = bool? 255 : 0; b = bool? 255 : 0; img[(x+y*w)*3+2] = (unsigned char)(r); img[(x+y*w)*3+1] = (unsigned char)(g); img[(x+y*w)*3+0] = (unsigned char)(b); } } 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 ); bmpfileheader[ 3] = (unsigned char)(filesize>> 8); bmpfileheader[ 4] = (unsigned char)(filesize>>16); bmpfileheader[ 5] = (unsigned char)(filesize>>24); bmpinfoheader[ 4] = (unsigned char)( w ); bmpinfoheader[ 5] = (unsigned char)( w>> 8); bmpinfoheader[ 6] = (unsigned char)( w>>16); bmpinfoheader[ 7] = (unsigned char)( w>>24); bmpinfoheader[ 8] = (unsigned char)( h ); bmpinfoheader[ 9] = (unsigned char)( h>> 8); bmpinfoheader[10] = (unsigned char)( h>>16); bmpinfoheader[11] = (unsigned char)( h>>24); f = fopen("img.bmp","wb"); fwrite(bmpfileheader,1,14,f); fwrite(bmpinfoheader,1,40,f); for(int i=0; i<h; i++) { fwrite(img+(w*(h-i-1)*3),3,w,f); fwrite(bmppad,1,(4-(w*3)%4)%4,f); } free(img); fclose(f); return 0; }
This code takes a boolean matrix matrix and creates a monochrome BMP image with a specified width (w) and height (h). It converts the boolean values to pixel values and writes the BMP file to the disk.
The above is the detailed content of How to Create a Monochrome BMP Image from a Boolean Matrix in Pure C/C ?. For more information, please follow other related articles on the PHP Chinese website!