写一个C++函数,帮我读取bmp图像
时间: 2024-05-06 11:21:48 浏览: 8
好的,您可以使用以下C函数来读取bmp图像:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct {
int width;
int height;
uint8_t* pixels;
} BMPImage;
BMPImage* read_bmp(const char* filename) {
FILE* file = fopen(filename, "rb");
if (file == NULL) return NULL;
// Read BMP header
uint8_t header[54];
fread(header, sizeof(header), 1, file);
// Check if file is a BMP image
if (header[0] != 'B' || header[1] != 'M') return NULL;
// Read image dimensions
int width = *(int*)&header[18];
int height = *(int*)&header[22];
// Read image data
int offset = *(int*)&header[10];
int size = *(int*)&header[34];
uint8_t* pixels = (uint8_t*)malloc(size);
fseek(file, offset, SEEK_SET);
fread(pixels, size, 1, file);
// Create BMP image struct
BMPImage* image = (BMPImage*)malloc(sizeof(BMPImage));
image->width = width;
image->height = height;
image->pixels = pixels;
// Return image
return image;
}
int main(void) {
BMPImage* image = read_bmp("image.bmp");
if (image == NULL) return 1;
printf("Width: %d\nHeight: %d\n", image->width, image->height);
free(image->pixels);
free(image);
return 0;
}
```
该函数会读取指定文件名的BMP图像,并返回一个BMPImage结构体,包含图像的宽度、高度和像素数据。您可以以适当的方式使用这些数据进行进一步的处理。