简体   繁体   English

如何将.bmp图像数据保存到数组并获取每个像素的RGB值?

[英]How to save .bmp image data to array and get RGB values of each pixel?

I am creating a program that can read a bmp image and calculate the percentage of red, blue and green color on it. 我正在创建一个程序,该程序可以读取bmp图像并计算其上的红色,蓝色和绿色的百分比。 I have searched a lot but haven't understood that from which byte does the image data exactly begins and how to get the RGB values of the pixels? 我进行了很多搜索,但还不了解图像数据从哪一个字节开始,以及如何获取像素的RGB值?

#include<stdio.h>

typedef struct {
unsigned int fileSize;
unsigned int offset;
unsigned int reserved;
char signature[2];
} BmpHeader;

typedef struct {
unsigned short bitDepth;
unsigned int compressedImageSize;
unsigned int compression;
unsigned int headerSize;
unsigned int height;
unsigned int horizontalResolution;
unsigned int importantColors;
unsigned int numColors;
unsigned short planeCount;
unsigned int verticalResolution;
unsigned int width;
} BmpImageInfo;

typedef struct {
unsigned char blue;
unsigned char green;
unsigned char red;
} Rgb;

int main(void) {
 BmpHeader header;
 BmpImageInfo info;



 char filename[40];
 printf("Enter file name : ");scanf("%s", filename);
 FILE *fp;
 fp = fopen(filename, "rb");
 fread(&header, 1, sizeof(BmpHeader), fp);
 fread(&info, 1, sizeof(BmpImageInfo), fp);

 printf("%u", info.height);





 getchar();
 return 0;

}

WHY AM I GETTING THE WRONG HEIGHT??? 为什么我得到了错误的身高??

This link is to the wiki page that describes the .bmp image format. 该链接指向描述.bmp图像格式的Wiki页面。 Things to note: 注意事项:

  1. the .bmp image uses little endian for all fields .bmp图像对所有字段都使用小端
  2. there are no gaps/filler between fields, so needs to be treated as a char array and/or use #pragma pack for the struct that describes the image. 字段之间没有空格/填充符,因此需要将其视为char数组和/或将#pragma pack用于描述图像的结构。 I prefer the char array method. 更喜欢char数组方法。
  3. there is a field that describes the number of bits in each pixel. 有一个字段描述每个像素的位数。 you will need that info when copying the data. 复制数据时,您将需要该信息。 also note that a 24bits per pixel image can have a 4th field for opacity, so then each pixel would actually be 32 bits. 还要注意,每像素24位的图像可以具有第4个不透明度字段,因此每个像素实际上是32位。

Here is the link . 这是链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM