在沒有外部函式庫的情況下用純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中文網其他相關文章!