C语言将一张图片的rgb信息保存本地
时间: 2024-06-12 22:05:40 浏览: 83
以下是C语言将一张图片的RGB信息保存本地的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BMP_HEADER_SIZE 54
// 读取BMP文件头信息
void read_bmp_header(FILE *file, int *width, int *height, int *data_size) {
unsigned char header[BMP_HEADER_SIZE];
fread(header, 1, BMP_HEADER_SIZE, file);
*width = *(int*)&header[18];
*height = *(int*)&header[22];
*data_size = *(int*)&header[34];
}
// 读取BMP图片的RGB数据
void read_bmp_rgb(FILE *file, unsigned char *data, int data_size) {
fread(data, 1, data_size, file);
}
// 保存RGB数据到本地文件
void save_rgb_to_file(unsigned char *data, int data_size, char *file_path) {
FILE *file = fopen(file_path, "wb");
if (file == NULL) {
printf("Failed to open file for writing.\n");
return;
}
fwrite(data, 1, data_size, file);
fclose(file);
}
int main() {
char *file_path = "image.bmp";
FILE *file = fopen(file_path, "rb");
if (file == NULL) {
printf("Failed to open file.\n");
return 0;
}
int width, height, data_size;
read_bmp_header(file, &width, &height, &data_size);
printf("Image size: %d x %d, data size: %d\n", width, height, data_size);
unsigned char *data = (unsigned char*)malloc(data_size);
read_bmp_rgb(file, data, data_size);
fclose(file);
char *output_file_path = "output.rgb";
save_rgb_to_file(data, data_size, output_file_path);
printf("RGB data saved to file: %s\n", output_file_path);
free(data);
return 0;
}
```
该示例代码使用了Windows BMP文件格式,并假设图像数据是24位RGB格式。如果需要处理其他格式的图像,请参考相应的格式规范进行修改。
阅读全文