首页 >后端开发 >C++ >如何在纯 C/C 中从布尔矩阵编写 BMP 图像?

如何在纯 C/C 中从布尔矩阵编写 BMP 图像?

Barbara Streisand
Barbara Streisand原创
2024-12-19 09:06:10308浏览

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