Yousuf
Yousuf

Reputation: 19

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. 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?

#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???

Upvotes: 0

Views: 1771

Answers (1)

user3629249
user3629249

Reputation: 16540

This link is to the wiki page that describes the .bmp image format. Things to note:

  1. the .bmp image uses little endian for all fields
  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. I prefer the char array method.
  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.

Here is the link.

Upvotes: 3

Related Questions