Reputation: 3
I have been working on creating my own BMP reader in c and I managed to read the Header and the HeaderInfo but when I read the image data to my array of struct I get wrong output. the expected output is 10, what i get is 20. Here is my code:
#include<stdio.h>
typedef struct
{
unsigned char Red;
unsigned char Green;
unsigned char Blue;
} pixel;
#pragma pack(2) /*2 byte packing */
typedef struct
{
unsigned short int type;
unsigned int size;
unsigned short int reserved1,reserved2;
unsigned int offset;
}header;
typedef struct
{
unsigned int size;
int width,height;
unsigned short int bits;
unsigned int compression;
unsigned int pixelsize;
int xresolution,yresolution;
unsigned int ncolors;
unsigned int importantcolors;
}headerInfo;
void main()
{
header head;
headerInfo headInfo;
int counter=0;
FILE *leftpixel;
leftpixel = fopen("left.bmp","rb+");
if(leftpixel==NULL)
{
printf("Error opening first file");
}
fread(&head,1,sizeof(head),leftpixel);
printf("%x ",head.type);
printf("%u ",head.size);
printf("%u ",head.offset);
printf("\n");
fread(&headInfo,1,sizeof(headInfo),leftpixel);
printf("%d ",headInfo.width);
printf("%d ",headInfo.height);
printf("\n");
fseek(leftpixel,54,SEEK_SET);
pixel im[480][640];
int i,j;
for (i = 0; i < 480; i++) {
for (j = 0; j < 640; j++) {
fread(&im[i][j], sizeof(unsigned char),headInfo.pixelsize, leftpixel);
if(im[i][j].Red>(im[i][j].Green+im[i][j].Blue))
{
counter++;
}
}
}
printf("counter =%d ", counter);
printf("\n");
}
Upvotes: 0
Views: 5878
Reputation: 88
You should never use hard-coded constants as in fseek(leftpixel,54,SEEK_SET)
; extract offset to pixmap from bfOffBits field of the header and in other situations use nformation from file header not your guesses. Also read comment from @V-X under the question.
Upvotes: 1