c语言读取bmp文件完整版
时间: 2023-07-18 09:11:08 浏览: 125
以下是C语言读取BMP文件的完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
#pragma pack(push, 1)
typedef struct {
unsigned short type;
unsigned int size;
unsigned short reserved1;
unsigned short reserved2;
unsigned int offset;
} BMPFileHeader;
typedef struct {
unsigned int size;
int width;
int height;
unsigned short planes;
unsigned short bitCount;
unsigned int compression;
unsigned int sizeImage;
int xPelsPerMeter;
int yPelsPerMeter;
unsigned int clrUsed;
unsigned int clrImportant;
} BMPInfoHeader;
#pragma pack(pop)
void readBMP(char* filename) {
FILE* file = fopen(filename, "rb");
if (!file) {
printf("Failed to open file: %s\n", filename);
return;
}
BMPFileHeader fileHeader;
fread(&fileHeader, sizeof(fileHeader), 1, file);
if (fileHeader.type != 0x4D42) {
printf("Invalid BMP file.\n");
fclose(file);
return;
}
BMPInfoHeader infoHeader;
fread(&infoHeader, sizeof(infoHeader), 1, file);
if (infoHeader.bitCount != 24) {
printf("Only 24-bit BMP files are supported.\n");
fclose(file);
return;
}
int dataSize = infoHeader.width * infoHeader.height * 3;
unsigned char* data = (unsigned char*)malloc(dataSize);
if (!data) {
printf("Failed to allocate memory.\n");
fclose(file);
return;
}
fseek(file, fileHeader.offset, SEEK_SET);
fread(data, dataSize, 1, file);
fclose(file);
// Do something with the data here...
free(data);
}
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
readBMP(argv[1]);
return 0;
}
```
该代码使用了两个结构体来分别表示BMP文件头和BMP信息头。通过fread函数,我们可以从文件中读取这些结构体的数据。读取完文件头和信息头之后,我们需要确保该BMP文件是一个24位的BMP文件,因为该代码只支持24位BMP文件。接下来,我们可以使用fseek和fread函数读取BMP文件中的像素数据。
请注意,该代码只能读取24位BMP文件,并且不支持压缩。如果您需要读取其他类型的BMP文件,请根据需要修改代码。
阅读全文