在純 C/C 中建立單色 BMP 影像
點陣圖影像檔案廣泛用於儲存數位影像。本文解決了將布林矩陣寫入單色 BMP 檔案的需求,如果對應的矩陣元素為 true,則像素設為白色。
了解 BMP 標頭
BMP 檔案格式具有特定的標頭結構,其中包含有關影像的基本資訊。文件頭由兩部分組成:文件頭和資訊頭。
檔案頭
訊息標頭
建立單色BMP
建立單色BMP:
#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; }
此程式碼採用布林矩陣矩陣並建立具有指定寬度 (w) 和高度 (h) 的單色 BMP 影像。它將布林值轉換為像素值並將 BMP 檔案寫入磁碟。
以上是如何在純 C/C 中從布林矩陣建立單色 BMP 影像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!