在没有外部库的情况下用纯C/C编写BMP图像
在开发需要信息输出的算法时,需要在各种格式。一种常见的格式是 BMP 图像。本文解决了从布尔矩阵创建单色 BMP 图像的问题,其中真实元素表示为白色像素。
BMP 标头结构
BMP(位图)图像)文件由标题部分和后跟图像数据组成。标头包含有关图像尺寸、颜色深度和压缩格式的重要信息。以下是主要组件的细分:
代码从布尔矩阵生成 BMP 图像
以下代码片段演示了如何创建 BMP来自布尔矩阵的图像,而不依赖于外部库:
FILE *f; unsigned char *img = NULL; int filesize = 54 + 3*w*h; // w and h are image width and height // Allocate memory for image data img = (unsigned char *)malloc(3*w*h); memset(img,0,3*w*h); // Fill img byte array with pixel data for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int x = i, y = (h-1)-j; int r, g, b; // Color components // Set pixel color based on matrix element if (matrix[i][j]) { r = g = b = 255; // White pixel } else { r = g = b = 0; // Black pixel } // Write pixel color components to image data array 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); } } // Set BMP header values 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}; // Update file size bmpfileheader[ 2] = (unsigned char)(filesize ); bmpfileheader[ 3] = (unsigned char)(filesize>> 8); bmpfileheader[ 4] = (unsigned char)(filesize>>16); bmpfileheader[ 5] = (unsigned char)(filesize>>24); // Update image width and height 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); // Save BMP image to file 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); // Pad to 4-byte boundary } // Free resources free(img); fclose(f);
通过遵循此代码中概述的步骤,您可以成功地从布尔矩阵生成单色 BMP 图像,提供一种可视化和输出您的图像的方法算法的结果。
以上是如何在没有外部库的情况下在纯 C/C 中从布尔矩阵创建单色 BMP 图像?的详细内容。更多信息请关注PHP中文网其他相关文章!