I guess your problem is structure alignment
. You can refer to it here and here. To eliminate it use the #pragma
directive. So your structure declaration would be something like this:
#pragma pack(push) // push current alignment to stack
#pragma pack(1) // set alignment to 1 byte boundary
typedef struct
{
unsigned short int Type; /* Magic identifier */
unsigned int Size; /* File size in bytes */
unsigned short int Reserved1;
unsigned short int Reserved2;
unsigned int Offset; /* Offset to data (in B)*/
}HEADER; /* -- 14 Bytes -- */
typedef struct
{
unsigned int Size; /* Header size in bytes */
int Width;
int Height; /* Width / Height of image */
unsigned short int Planes; /* Number of colour planes */
unsigned short int Bits; /* Bits per pixel */
unsigned int Compression; /* Compression type */
unsigned int ImageSize; /* Image size in bytes */
int xResolution;
int yResolution;/* Pixels per meter */
unsigned int Colors; /* Number of colors */
unsigned int ImportantColors;/* Important colors */
}INFOHEADER; /* -- 40 Bytes -- */
typedef struct
{
unsigned char Red;
unsigned char Green;
unsigned char Blue;
}PIXEL;
#pragma pack(pop) // restore original alignment from stack
This correctly reads the width and height of BMP image. Further while reading image data, do it directly:
for( r=0; r<rows; r++ )
{
for( c=0; c<collumns; c++ ) // read pixel data from image
{
fread(&pixelarray[r][c] , 1, sizeof(PIXEL), file);
pixelnum++;
}
}