Writing BMP Images in Pure C/C Without External Libraries
In certain computational algorithms, creating visual outputs can be essential for analysis and presentation. When dealing with boolean matrices, generating monochrome BMP images can be a suitable method to visualize the data. However, constructing a BMP image from scratch without relying on external libraries can seem daunting.
This task involves defining the image header and organizing the pixel data in a specific format. The BMP header provides crucial information about the image, including its width, height, and color depth. For a monochrome image, each pixel can be represented by a single bit, indicating its color (white or black).
Here's a detailed code snippet that demonstrates how to write a boolean matrix as a monochrome BMP image using pure C/C :
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { // Image dimensions int width = 100, height = 100; // Boolean matrix representing the image data bool matrix[width][height]; // File pointer for writing the BMP image FILE* f = fopen("image.bmp", "wb"); // BMP file header unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0}; // BMP image data header unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 1,0}; // Set file size in header bmpfileheader[ 2] = (width + 7) / 8 * height; // Adjust image width and height in header bmpinfoheader[ 4] = width; bmpinfoheader[ 8] = height; // Write the BMP header and image data fwrite(bmpfileheader, 1, 14, f); fwrite(bmpinfoheader, 1, 40, f); // Iterate over the matrix and write each row as a bitmask for (int i = 0; i < height; i++) { // Create a bitmask for the current row unsigned char rowdata = 0; for (int j = 0; j < width; j++) { if (matrix[j][i]) { // Set the corresponding bit in the bitmask rowdata |= 1 << (7 - j); } } fwrite(&rowdata, 1, 1, f); } fclose(f); return 0; }
In this code, the BMP header includes the image width and height as part of the header data. After writing the header, the code iterates over each row of the boolean matrix and constructs a bitmask to represent the corresponding pixel values. Each bit in the bitmask indicates whether the pixel is white or black. By writing these bitmasks sequentially, the generated BMP file will accurately display the boolean matrix as a monochrome image.
The above is the detailed content of How to Create Monochrome BMP Images from Boolean Matrices in Pure C/C Without External Libraries?. For more information, please follow other related articles on the PHP Chinese website!