生成单通道bmp文件C语言代码
时间: 2023-12-10 15:03:44 浏览: 24
以下是生成单通道bmp文件的C语言代码:
```c
#include <stdio.h>
#pragma pack(push, 1)
typedef struct {
char signature[2];
uint32_t fileSize;
uint32_t reserved;
uint32_t dataOffset;
} BMPFileHeader;
typedef struct {
uint32_t headerSize;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bitsPerPixel;
uint32_t compression;
uint32_t imageSize;
int32_t xPixelsPerMeter;
int32_t yPixelsPerMeter;
uint32_t numColors;
uint32_t importantColors;
} BMPImageHeader;
#pragma pack(pop)
void generateBMP(char* filename, uint8_t* data, int width, int height) {
BMPFileHeader fileHeader = {
.signature = {'B', 'M'},
.fileSize = sizeof(BMPFileHeader) + sizeof(BMPImageHeader) + width * height,
.reserved = 0,
.dataOffset = sizeof(BMPFileHeader) + sizeof(BMPImageHeader)
};
BMPImageHeader imageHeader = {
.headerSize = sizeof(BMPImageHeader),
.width = width,
.height = height,
.planes = 1,
.bitsPerPixel = 8,
.compression = 0,
.imageSize = width * height,
.xPixelsPerMeter = 0,
.yPixelsPerMeter = 0,
.numColors = 256,
.importantColors = 0
};
FILE* file = fopen(filename, "wb");
fwrite(&fileHeader, sizeof(fileHeader), 1, file);
fwrite(&imageHeader, sizeof(imageHeader), 1, file);
fwrite(data, sizeof(uint8_t), width * height, file);
fclose(file);
}
int main() {
// 生成一张100x100的单通道bmp图像,像素值为0
uint8_t data[10000] = {0};
generateBMP("test.bmp", data, 100, 100);
return 0;
}
```
代码中使用了结构体来表示BMP文件头和图像头,这是因为BMP文件使用了特定的格式。在生成BMP文件时,先计算文件头和图像头的内容,然后将数据写入文件中即可。这里只生成了单通道BMP图像,即每个像素只有一个8位的灰度值,其他类型的BMP图像生成方式类似。