首頁 >後端開發 >C++ >如何在純 C/C 中從布林矩陣編寫 BMP 影像?

如何在純 C/C 中從布林矩陣編寫 BMP 影像?

Barbara Streisand
Barbara Streisand原創
2024-12-19 09:06:10239瀏覽

How to Write a BMP Image from a Boolean Matrix in Pure C/C  ?

在沒有外部函式庫的情況下用純C/C 寫BMP 影像

使用布林矩陣建立輸出時,需要將其寫入入出現一個BMP 檔。這涉及如果相應的矩陣元素為真,則創建一個像素標記為白色的單色圖像。挑戰仍然在於理解 BMP 標頭結構及其寫入過程。

為了解決這個問題,解決方案涉及創建三個 2D 數組:紅色、綠色和藍色,每個數組代表基於矩陣的像素值。以下程式碼示範了該方法:

FILE *f;
unsigned char *img = NULL;
int filesize = 54 + 3 * w * h; // Width and height represented as w and h

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++) {
        int x = i, y = (h - 1) - j; // Flipping the image vertically
        int r = red[i][j] * 255;
        int g = green[i][j] * 255;
        int b = blue[i][j] * 255;
        // Clamping RGB values between 0-255
        if (r > 255) r = 255;
        if (g > 255) g = 255;
        if (b > 255) b = 255;
        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);
    }
}

// Define BMP headers
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};

// Populate BMP header values
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); // Padding to ensure 4-byte alignment
}

free(img);
fclose(f);

此方法提供了從布林矩陣寫入 BMP 檔案的全面解決方案,而無需依賴外部程式庫。標頭結構經過精心定義,程式碼確保正確的像素格式和填充,從而產生可由標準影像檢視器開啟的有效 BMP 影像。

以上是如何在純 C/C 中從布林矩陣編寫 BMP 影像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn